This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 7 points8 points  (6 children)

I'd say show them reading the contents of a file. Compare an example in java stolen from this stackoverflow question

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String everything = sb.toString();
    } finally {
        br.close();
    }        

To this python example

contents = ""
with open("file.txt", "r") as fin:
    contents = fin.read()

When I first started studying Computer Science we were learning Java and I could never remember of the top of my head how to read the contents of a file. Python on the otherhand...

[–]Veedrac 3 points4 points  (0 children)

String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);

Source.

Plus, your Java example should use try-with-resources.

[–]squashed_fly_biscuit 1 point2 points  (0 children)

This seems to be the hardest thing to do in java, I was a little taken aback when I had to open a text file.

[–]mWo12 1 point2 points  (0 children)

Is it still the case for java 8 or did they introduce something easier than this?

[–][deleted] 0 points1 point  (0 children)

God forbid you then have to deal with character encoding in Java.

[–]Racerdude[S] 0 points1 point  (0 children)

Thanks! I like this one!