-
Notifications
You must be signed in to change notification settings - Fork 8
How to Write File in Java
Ramesh Fadatare edited this page Jul 18, 2018
·
2 revisions
In this example, we will use BufferedWriter class to write the file. There are other Stream Ouput classes to write file but in this example we will focus on frequently used BufferedWriter.
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Java program demonstrates how to write file in Java.
* @author javaguides.net
*/
public class WriteFileExample {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteFileExample.class);
public static void main(String[] args) {
writeFile();
}
// Write file using BufferedWriter
public static void writeFile() {
try (BufferedWriter bw = new BufferedWriter(
new FileWriter("C:/workspace/java-io-guide/sample.txt"))) {
String content = "This is the content to write into file\n";
bw.write(content);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}
https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html