How do I Create, Write and Read txt Files in Java?

By

What's the simplest way to create and write to a (text) file in Java?

1 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();
        }
    }