2

If without converting the below lines to string can it work fine? Do I need to use the Stream <String> in front of the lines = Files.lines(Paths.get("c:\\demo.txt")); to convert the file lines into strings? Or it is unnecessary to do that ?

lines = Files.lines(Paths.get("c:\\demo.txt"));
lines.forEach(System.out::println);
lines.close();

I'm new to Java, I don't really know about the use of Stream <String> in the coding. Is it meant to convert the lines to strings or something else? So I posted this question.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
李晓东
  • 83
  • 6
  • Files.lines is already returning a string list (I'm pretty sure at least). If you mean storing it in a variable, you should if you plan to do more than one operation. – Ryan_DS Sep 25 '18 at 16:41
  • So if I write `final Path data = Paths.get("c:\\demo.txt"); Files.lines(data).forEach(System.out::println);` is there any wrong in the coding? – 李晓东 Sep 25 '18 at 17:06
  • 2
    `try(Stream lines = Files.lines(Paths.get("c:\\demo.txt")) { lines.forEach(System.out::println); }` is the correct way to safely close the stream and avoid using the variable after it has been closed. – Holger Sep 26 '18 at 06:23

1 Answers1

2

Files#lines already returns a Stream<String>. No conversion is necessary.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • So if I write `final Path data = Paths.get("c:\\demo.txt"); Files.lines(data).forEach(System.out::println);` is there any wrong in the coding? – 李晓东 Sep 25 '18 at 17:01
  • @李晓东 The only thing wrong there is that you won't be closing the file at the end. See, e.g., the [explanation here](https://stackoverflow.com/q/34072035/2422776). – Mureinik Sep 25 '18 at 18:37
  • Do you mean that I will need to close the file in the end? is it the only mistake in this coding? – 李晓东 Sep 26 '18 at 02:05
  • @李晓东 yes, exactly. – Mureinik Sep 26 '18 at 02:56