In this article, we introduce you Java 8 Write to File Examples using Java 8 APIs along with Files.newBufferedWriter, Files.write and Files.newOutputStream.
Let’s deeper via examples below:
Write to file using BufferedWriter
You can use the newBufferedWriter(Path, Charset, OpenOption…) method to write to a file using a BufferedWriter.
The following code snippet shows how to create a file encoded in “US-ASCII” using this method:
1 2 3 4 5 6 7 8 |
Path path = Paths.get("D:/test.txt"); //1st way String str1 = "Using newBufferedWriter method!\n"; try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { writer.write(str1, 0, str1.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); } |
Write to file using Files.write()
You can use Files.write method to write bytes, or lines, to a file.
1 2 3 4 5 6 7 |
//2nd way String str2 = "Using Files.write method !\n"; try { Files.write(path, str2.getBytes(StandardCharsets.UTF_8),CREATE,APPEND); } catch (IOException x) { System.err.println(x); } |
Writing to file using Stream I/O
You can create a file, append to a file, or write to a file by using the newOutputStream(Path, OpenOption…) method. This method opens or creates a file for writing bytes and returns an unbuffered output stream.
1 2 3 4 5 6 7 8 9 10 |
//3rd way String str3 = "Using newOutputStream method\n"; byte data[] = str3.getBytes(StandardCharsets.UTF_8); try (OutputStream out = new BufferedOutputStream( Files.newOutputStream(path, CREATE, APPEND))) { out.write(data, 0, data.length); } catch (IOException x) { System.err.println(x); } |
Output
That’s all about the Java 8 Write to File Examples.
References
Files (Java Platform SE 8 )
Download the complete source code, click link below
Java8WriteFile.zip (265 downloads)