Why are there no Files.readAllLines (String path) files in java 7?

I am trying to learn the nio 2 package in Java 7 and I came across the Files.readAllLines(Path p, Charset cs) method Files.readAllLines(Path p, Charset cs) . I believe this is very useful, but I believe there should be a version without the cs parameter, like:

  public static List<String> readAllLines(String path) throws IOException { return readAllLines(Paths.get(path), Charset.defaultCharset());} 

I am convinced that in most cases the method will be called using Charset by default, so why not shorcut. Is there something that I am missing in encodings that would justify the lack of this method? I am very surprised because Scala has this option:

 Source.fromFile("fileName").getLines 

so I don’t understand why Java should not. Any kinds?

+4
source share
2 answers

[...] in most cases, the method will be called using the default Charset,

Not really. Most of the time it will be called with an encoding in which you expect the file to be encoded. Usually these days it is UTF-8:

 Files.readAllLines("fileName", StandardCharsets.UTF_8) 

Your application can be run on multiple platforms and operating systems using different default encodings. You do not want your application to crash just because of this.

I think this is a good choice, fixing the wrong decisions from the past. Many older Java methods use the default system encoding, causing inconsistent behavior or an application, for example. between Windows and Linux. Forcing the choice of character encoding just makes your application more portable and secure.


By the way, since you mention the io.Source class - note that it returns an iterator instead of List<String> , as the Files class does. Advantage: the file is loaded lazily, not all at once until the huge ArrayList<String> . Disadvantage: you must close the source manually (which you cannot do in the code snippet).

+12
source

You will need to ask the designers, but most likely they share my opinion that reading entire files into memory is not something that needs to be encouraged. It does not scale, and it introduces unnecessary time and space. Process the file one at a time.

0
source

Source: https://habr.com/ru/post/1437538/


All Articles