---
title: "Easiest way to read write files in java 8"
author: "kaqi"
date: "2017-10-25T15:46:36Z"
tags: []
categories: ["编程语言"]
slug: "easiest-way-to-read-write-files-in-java-8"
draft: false
lastmod: "2018-05-22T17:35:53Z"
id: 2397593
url: "https://kaqi.iteye.com/blog/2397593"
---

```
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"));
        }
    }
```