I'm tryting to learn the nio 2
package in Java 7 and i stumbled upon the Files.readAllLines(Path p, Charset cs)
method. I find it very useful, but i'm of the opinion that there should be a version without the cs
parameter, just like :
public static List<String> readAllLines(String path)
throws IOException
{ return readAllLines(Paths.get(path), Charset.defaultCharset());}
I convinced that most of the time the method will be called with the default Charset anyway, so why no the shorcut. Is there anything i'm missing about charsets that would justify not having this method? I'm quite surprised because Scala has this option:
Source.fromFile("fileName").getLines
so i don't see why Java shouldn't. Any views?
[...] most of the time the method will be called with the default Charset anyway,
Not really. Most of the time it will be called with the charset that you expect the file to be encoded in. Typically these days it is UTF-8:
Files.readAllLines("fileName", StandardCharsets.UTF_8)
Your application can be executed on several platforms and operating systems, using different default character encoding. You don't want your application to break just because of that.
I think it's a good choice, fixing wrong desing decisions from the past. Many old Java methods use default system encoding, causing inconsistent behaviour or application e.g. between Windows and Linux. Forcing to choose the character encoding simply makes your application more portable and safer.
BTW since you are mentioning io.Source
class - note that it returns an iterator instead of a List<String>
as Files
class does. The advantage: file is loaded lazily, not all at once to huge ArrayList<String>
. Disadvantage: you must close the source manually (which you can't do in your code snippet).