How to Read and Write TXT File in Java


In this example we will show the methods to read and write TXT File in Java.

Source Code

1) Read

package com.beginner.examples;

import java.io.*;

public class ReadTxtExample {

	public static void main(String[] args) {

		String path = "example.txt";
		String line = "";
        try
        {
        
    		FileReader reader = new FileReader(path);
    		BufferedReader br = new BufferedReader(reader);
    		while ((line = br.readLine()) != null) 
    		{
    			System.out.println(line);
    		}
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Output:

test
read

2) Write

package com.beginner.examples;

import java.io.*;

public class WriteTxtExample {

	public static void main(String[] args) {

        try
        {
        	 File path = new File("example.txt");
             path.createNewFile();
             FileWriter writer = new FileWriter(path);
             BufferedWriter bw = new BufferedWriter(writer);  
             bw.write("testrnwrite");
             bw.flush();
             bw.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments