Whole text file to a String in Java

后端 未结 10 2267
遇见更好的自我
遇见更好的自我 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条回答
  •  心在旅途
    2020-12-01 16:11

    In Java 8 (no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.

    try (Stream lines = Files.lines(myPath)) {
        list = lines.collect(Collectors.joining(", "));
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    

提交回复
热议问题