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

How to Create Temp File or Directory in Java
May 09, 2020
OpenAI Unveils Successor to ChatGPT: GPT-4
Mar 17, 2023
Android Google Maps Tutorial with Example
May 31, 2020
Trump Allows US Companies to Work with Huawei Again
Jul 01, 2019
Android Upload Image to Server Using Retrofit
Dec 05, 2019
8 Reasons Coding for Kids is Not Just Another Fad
Jul 21, 2020
Java Database Connectivity (JDBC) with MySQL Tutorial
Dec 29, 2019
Types of Software Testing
Jul 20, 2019
An introduction to cloud computing right from the basics up to IaaS, PaaS and SaaS
Jul 03, 2020