Tackle verbosity and static import

Alan Bateman Alan.Bateman at oracle.com
Thu Apr 14 11:18:13 PDT 2011


Rémi Forax wrote:
> Playing a little bit with NIO file API, I come with this snippet for 
> printing
> all lines of a file.
>
>   public static void main(String[] args) throws IOException {
>     for(String line: readAllLines(get("foo.txt"), defaultCharset())) {
>       System.out.println(line);
>     }
>   }
>
> The trick is to abuse of static import, the whole file is:
>
> import static java.nio.file.Files.*;
> import static java.nio.file.Paths.*;
> import static java.nio.charset.Charset.*;
>
> import java.io.IOException;
>
> public class LessVerbosity {
>   public static void main(String[] args) throws IOException {
>     for(String line: readAllLines(get("foo.txt"), defaultCharset())) {
>       System.out.println(line);
>     }
>   }
> }
>
> In my opinion, it shows that Paths.get should be renamed to 
> Paths.getPath()
> to be meaningful if used with static import.
>
> Also, it should be cool to have an overload version of Files.readAllLines
> that doesn't require a charset and use the default charset.
>
> Rémi
>
Yes, definitely pushing static import a bit too far :-)  The Files class 
is well suited for static import but the Paths class isn't. I don't 
think Paths.get is too bad but in any case, it's probably too late now 
to consider renaming these methods.

On the charset, did you see Mike Duigou's proposal on core-libs-dev to 
define a class with constants for the standard charsets? That should 
work well with readAllLines and several other methods, eg: 
readAllLines(path, UTF_8);

-Alan.





More information about the nio-dev mailing list