What's the simplest way to create and write to a (text) file in Java?
How do I Create, Write and Read txt Files in Java?
By Eric Murithi Muchenah1 Answers
Java has createNewFile() method that returns a boolean value. It returns true if the file is created and false if the file exists. Use the following code to create a file.
public class CreateTxtFile {
public static void main(String[] args) {
try {
File myFile = new File("sample_file.txt");
if (myFile.createNewFile()) {
System.out.println("File has been created: " + myFile.getName());
} else {
System.out.println("The file exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use the following to code to write content on a text file:
public void writeTxtFile(String fileName){
try {
FileWriter writer = new FileWriter(fileName, true);
writer.write("This is a Java code");
writer.write("\r\n");
writer.write("This is another line!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Use the following to code to read the contents of a text file:
public void readTxtFile(String fileName) {
try {
FileReader reader = new FileReader(fileName);
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Subscribe to our newsletter
Random Blogs

Writing your First JavaFX Application
Nov 09, 2019
What is Oracle PL/SQL? - An Introduction
Jun 21, 2020
The Best Cloud Computing Books for Beginners
Jul 19, 2020
The Best Java Books for Beginners
Jul 30, 2019
PHP RESTful Web Services Tutorial With Example
Jul 26, 2020
Python vs. Java: Uses, Performance, Learning
Aug 30, 2020
SELECT INTO Statement in PL/SQL
Jun 27, 2020
Android Upload Image to Server Using Retrofit
Dec 05, 2019
JavaFX vs HTML5
Oct 03, 2019