Home » Development » Reading from and writing to a text file by Java

Reading from and writing to a text file by Java

It might easily get complicated to read from and write to a text file if you don’t use the appropriate objects. What are these objects:

The objects for reading from and writing to a file in Java
The objects for reading from and writing to a file in Java

Here is the complete code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Main
{
    public static void main(String[] args)
    {
        readFile();
        writeFile();
    }

    // Reading from the text file
    public static void readFile()
    {
        BufferedReader br;
        try
        {
            br = new BufferedReader(new FileReader("C:\\test.txt"));

            String line = br.readLine();
            while (line != null)
            {
                System.out.println(line);
                line = br.readLine();
            }
            br.close();

        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    // Writing to the text file
    public static void writeFile()
    {
        PrintWriter pw = null;
        try
        {
            pw = new PrintWriter(new FileWriter("C:\\test2.txt"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        pw.print("content");
        pw.close();
    }
}

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment