Search code examples
javacopybufferfilewriter

copy from existing file to another file using buffer


copy_file.java

package IOstream;
import java.io.*;
import java.nio.Buffer;
public class copy_file {
    public static void main(String[] args) {
        String str = "";

        File f1 = new File("first.txt");
        File f2 = new File("sudani.txt");
        try {
            FileReader fr = new FileReader(f1);
            BufferedReader br = new BufferedReader(fr);
            FileWriter fw=new FileWriter(f2);
            BufferedWriter bw = new BufferedWriter(fw);
            while(str!=null)
            {
                str= br.readLine();
                bw.write(str);
                bw.newLine();
                System.out.println(str);
            }
            br.close();
            bw.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

Here I want to copy one file to another file but I can just read the file can't copy to another file.

I got java.lang.NullPointerException


Solution

  • while((str=br.readLine())!=null)
                {
                    bw.write(str);
                    bw.newLine();
                    System.out.println(str);
                }
    

    Do flush your BufferedWriter too. Hope it helps :)