Whole text file to a String in Java

后端 未结 10 2245
遇见更好的自我
遇见更好的自我 2020-12-01 15:44

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data =          


        
10条回答
  •  -上瘾入骨i
    2020-12-01 16:24

    Java 7 improves on this sorry state of affairs with the Files class (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:

    List fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);
    

    Or into one String:

    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    // or equivalently:
    StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));
    

    If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?

提交回复
热议问题