Close

Java IO & NIO - Files.newBufferedWriter Examples

Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Methods:

public static BufferedWriter newBufferedWriter(Path path,
                                               Charset cs,
                                               OpenOption... options)
                                        throws IOException

Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.

Parameters:
path - the path to the file
cs - the charset to use for encoding
options - options specifying how the file is opened
Returns:
a new buffered writer, with default buffer size, to write text to the file



public static BufferedWriter newBufferedWriter(Path path,
                                               OpenOption... options)
                                        throws IOException

Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner.

Parameters:
path - the path to the file
options - options specifying how the file is opened
Returns:
a new buffered writer, with default buffer size, to write text to the file


Examples


        String name = multipartFile.getOriginalFilename();
BufferedWriter w = Files.newBufferedWriter(Paths.get("d:\\filesUploaded\\" + name));
w.write(new String(multipartFile.getBytes()));
w.flush();
Original Post




package com.logicbig.example.files;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class NewBufferedWriterExample {

public static void main(String... args) throws IOException {
Path dirPath = Files.createTempDirectory("test dir");
Path filePath = dirPath.resolve("test-file.txt");
System.out.println("File to write: " + filePath);
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath,
StandardOpenOption.CREATE_NEW)) {
bufferedWriter.write("line 1 \n");
bufferedWriter.write("line 2 \n");
}
//reading
System.out.println("Reading lines: ");
Files.lines(filePath).forEach(System.out::println);


}
}

Output

File to write: C:\Users\Joe\AppData\Local\Temp\test dir8922495571208510561\test-file.txt
Reading lines:
line 1
line 2




See Also