Search code examples
javafilereaderfilewriter

File Writer and File Reader error


I have this code to read from a text file and then modify it. Then write the modified content to another text file. I am getting a null pointer exception at out.write(read); And also, not all lines are being written, can some one help me please. Thank you

import java.util.*;
import java.io.*;

public class File
{
    BufferedReader in;
    BufferedWriter out;
    String read;

    public File()
    {
        try {
            in = new BufferedReader(new FileReader("myFile.txt"));
            Scanner scan = new Scanner(in);
            out = new BufferedWriter(new FileWriter("output.txt"));

            while (scan.hasNext()) {
                read = in.readLine();
                //Write codes to modify file here
                //___codes not written yet______//
                out.write(read);
                scan.next();
                System.out.println("file output: " + read);                 
            }
            out.close();
            in.close();
        } catch (IOException e) {
            System.out.println("There was a problem:" + e);
        }
    }

    public static void main(String[] args)
    {
        File File = new File();
    }
}

Solution

  • try

    while((read = in.readLine()) != null)
    

    instead of

    while (scan.hasNext())