Using Java 8, what is the most preferred and concise way of printing all the lines in a file?

前端 未结 3 1438
醉酒成梦
醉酒成梦 2020-12-15 23:17

What is the most preferred and concise way to print all the lines in a file using the new Java 8?

The output must be a copy of the file, line for line as in:

相关标签:
3条回答
  • 2020-12-16 00:04

    This uses the new Stream with a lambda in a try enclosure.

    I would say it is the most preferred and concise way because:

    1) It will automatically close the stream when done and properly throw any exceptions.

    2) The output of this is lazy. Each line is read after the last line is processed. This is also is closer to the original Java streams based file handling spec.

    3) It prints each line in a manner that most closely resembles the data in the file.

    4) This is less memory intensive because it does not create an intermediate List or Array such as the Files.readAllLines(...)

    5) This is the most flexible, since the Stream object provided has many other uses and functions for working with the data (transforms, collections, predicates, etc.)

     try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
                stream.forEach(System.out::println);
     }
    

    If the path and charset are provided and the Consumer can take any Object then this works too:

     try (Stream stream = Files.lines(path,charset)) {
                stream.forEach(System.out::println);
     }
    

    With error handling:

     try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
                stream.forEach(System.out::println);
     } catch (IOException ex) {
            // do something with exception
     } 
    
    0 讨论(0)
  • 2020-12-16 00:04

    Here is a simple solution:

    System.out.println( new String(Files.readAllBytes(Paths.get("sample.java"))) );
    
    0 讨论(0)
  • 2020-12-16 00:08

    You don't really need Java 8:

    System.out.println(Files.readAllLines(path, charset));
    

    If you really want to use a stream or need a cleaner presentation:

    Files.readAllLines(path, charset).forEach(System.out::println);
    
    0 讨论(0)
提交回复
热议问题