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

Software Testing Interview Questions
Feb 01, 2020
Types of Software Testing
Jul 20, 2019
SELECT INTO Statement in PL/SQL
Jun 27, 2020
Safaricom Hacked Again
Oct 23, 2019
Android SQLite Database Example Tutorial Part I
Aug 06, 2020
Best JavaFX Libraries for Beautiful Apps
Jan 13, 2020
Best Programming Laptops for Coders
Nov 03, 2019
Swap Two Numbers Without a Third Variable in Java
Aug 22, 2019
How to Start a Website in 2020 With Easy Steps
Jan 02, 2020