`

Easiest way to read write files in java 8

 
阅读更多
Path path = Paths.get(getClass().getClassLoader()
      .getResource("fileTest.txt").toURI()); //relative to the class

String content = new String(Files.readAllBytes(path));
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
                stream.forEach(System.out::println);
            }


String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());

 

    public static String read(String fileName) throws IOException {
        InputStream resourceAsStream = FileUtility.class.getClassLoader().getResourceAsStream(fileName); // the filename is relative to the classpath root
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(resourceAsStream))) {
            return buffer.lines().collect(Collectors.joining("\n"));
        }
    }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics