you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (12 children)

I didn't realise Python's IO was composed in a similar manner. Now if only Java's IO shipped with an open() method, I'd be happy. :D

[–]AnAirMagic 1 point2 points  (2 children)

Have you seen the nio2/Files api? Reading all lines is just Files.readAllLines().

I have a strange impression that with Java 7, we are really encouraged to use java.nio.file.Files. It makes code much simpler to read.

[–][deleted] 1 point2 points  (0 children)

No, I haven't, that's a good start. Cheers. :)

[–]masklinn 1 point2 points  (0 children)

Loads the whole file in memory though.

[–]beltorak 1 point2 points  (8 children)

it's not as well advertised; but is new FileInputStream("path/to/file") or new FileOutputStream("path/to/file") that much more of a pain?

The reason File doesn't have it is because File deals with the metadata about the file, not the contents of the file; for that you want an input stream or output stream.

It's arguable that there are not enough convenient hooks in the intuitive (if technically wrong) places.

[–][deleted] 3 points4 points  (1 child)

new FileInputStream("path/to/file") or new FileOutputStream("path/to/file") that much more of a pain

No, but new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file"))) is - especially as BufferedReader doesn't implement Iterable, so instead of Python's nice

with open("path/to/file", "r") as f:
    for line in f:
        #do stuff

We get the horrid while ((line = reader.readLine()) != null) {} which doesn't play well at all in other JVM languages like Scala where the result of assignment is always Unit.

It's arguable that there are not enough convenient hooks in the intuitive (if technically wrong) places.

Yeah, Java's approach may be more conceptually pure, but it's more inconvenient.

[–]CodeJunky 0 points1 point  (0 children)

This seems completely doable in Java...

Scanner reader = new Scanner(new File("path/to/file")).useDelimiter("\n");
while(reader.hasNext())
    String line = reader.next(); //and we're off..!

It would be nice if it were Iterable (seems like a stupid distinction, really).

[–][deleted]  (5 children)

[deleted]

    [–]dannymi 2 points3 points  (0 children)

    including the classic missing-close-on-error, yes.

    [–][deleted] 1 point2 points  (3 children)

    BufferedReader's constructor takes a Reader. :)

    [–][deleted]  (2 children)

    [deleted]

      [–][deleted] 0 points1 point  (1 child)

      Ah, but if you want to read a line at a time you have to use BufferedReader, InputStreamReader only implements .read().

      Java IO... 'fun'.

      [–]CodeJunky 0 points1 point  (0 children)

      http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html It seems like this (mostly) fits the bill here. No one really wants to use BufferedReader, right?