Copying the Contents of One text file to Another in Java
Asked Answered
B

9

7

I am trying to copy the contents of one text file ("1.txt") which contains 2-3 integer numbers (ex: 1 2 3) to another text file ("2.txt") but I am getting the following error upon compilation

import java.io.*;
class FileDemo {
    public static void main(String args[]) {
      try {
          FileReader fr=new FileReader("1.txt");
          FileWriter fw=new FileWriter("2.txt");
          int c=fr.read();
          while(c!=-1) {
            fw.write(c);
          }
      } catch(IOException e) {
          System.out.println(e);
      } finally() { 
          fr.close();
          fw.close();
      }
    }
}

Command prompt:-

C:\Documents and Settings\Salman\Desktop>javac FileDemo.java
FileDemo.java:20: error: '{' expected
                finally()
                       ^
FileDemo.java:20: error: illegal start of expression
                finally()
                        ^
FileDemo.java:20: error: ';' expected
                finally()
                         ^
FileDemo.java:27: error: reached end of file while parsing
}
 ^
4 errors

But upon checking the code, I find that the finally() block is properly closed.

Brain answered 2/5, 2013 at 5:30 Comment(2)
remove the () in finally(). it should be finally { }Jeffers
Was the compiler message not clear enough? It says "FileDemo.java:20: error: '{' expected" and points an arrow at the offending character! When errors occur, it often pays off to read the output very well and think about what it means.Dardani
G
30

It's finally, not finally():

try {
    //...
} catch(IOException e) {
    //...
} finally {
    //...
}

By the way, you have an endless loop there:

int c=fr.read();
while(c!=-1) {
    fw.write(c);
}

You must read the data inside the loop in order to let it finish:

int c=fr.read();
while(c!=-1) {
    fw.write(c);
    c = fr.read();
}

In the finally block, your fr and fw variables can't be found since they're declared in the scope of the try block. Declare them outside:

FileReader fr = null;
FileWriter fw = null;
try {
    //...

Now, since they are initialized with null value, you must also do a null check before closing them:

finally {
    if (fr != null) {
        fr.close();
    }
    if (fw != null) {
        fw.close();
    }
}

And the close method on both can throw IOException that must be handled as well:

finally {
    if (fr != null) {
        try {
            fr.close();
        } catch(IOException e) {
            //...
        }
    }
    if (fw != null) {
        try {
            fw.close();
        } catch(IOException e) {
            //...
        }
    }
}

In the end, since you don't want to have a lot of code to close a basic stream, just move it into a method that handles a Closeable (note that both FileReader and FileWriter implements this interface):

public static void close(Closeable stream) {
    try {
        if (stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        //...
    }
}

In the end, your code should look like:

import java.io.*;
class FileDemo {
    public static void main(String args[]) {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("1.txt");
            fw = new FileWriter("2.txt");
            int c = fr.read();
            while(c!=-1) {
                fw.write(c);
                c = fr.read();
            }
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            close(fr);
            close(fw);
        }
    }
    public static void close(Closeable stream) {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch(IOException e) {
            //...
        }
    }
}

Since Java 7, we have try-with-resources, so code above could be rewritten like:

import java.io.*;
class FileDemo {
    public static void main(String args[]) {
        //this will close the resources automatically
        //even if an exception rises
        try (FileReader fr = new FileReader("1.txt");
             FileWriter fw = new FileWriter("2.txt")) {
            int c = fr.read();
            while(c!=-1) {
                fw.write(c);
                c = fr.read();
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
Godfry answered 2/5, 2013 at 5:32 Comment(1)
Great answer! Idiom I often see for the reading loop is: int c; while((c = fr.read()) != -1) { fw.write(c); } Not necessarily more readable but saves one line of code. You can also use the read(char[]) and write(char[]) methods to copy the complete contents in one statement (so no loop needed in your code).Dardani
G
4

More efficient way is...

public class Main {

public static void main(String[] args) throws IOException {
    File dir = new File(".");

    String source = dir.getCanonicalPath() + File.separator + "Code.txt";
    String dest = dir.getCanonicalPath() + File.separator + "Dest.txt";

    File fin = new File(source);
    FileInputStream fis = new FileInputStream(fin);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));

    FileWriter fstream = new FileWriter(dest, true);
    BufferedWriter out = new BufferedWriter(fstream);

    String aLine = null;
    while ((aLine = in.readLine()) != null) {
        //Process each line and add output to Dest.txt file
        out.write(aLine);
        out.newLine();
    }

    // do not forget to close the buffer reader
    in.close();

    // close buffer writer
    out.close();
}
} 
Gil answered 3/10, 2014 at 7:50 Comment(0)
T
0

Its a compilation error

public static void main(String args[])
    {
        try
        {
            FileReader fr=new FileReader("1.txt");
            FileWriter fw=new FileWriter("2.txt");
            int c=fr.read();
            while(c!=-1)
            {
                fw.write(c);
            }
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
        finally // finally doesn't accept any arguments like catch
        {   
            fr.close();
            fw.close();
        }

    }
Toper answered 2/5, 2013 at 5:32 Comment(0)
F
0

A Finally block shouldn't have the round parentheses.

Try:

import java.io.*;
class FileDemo
{
    public static void main(String args[])
    {
        try
        {
            FileReader fr=new FileReader("1.txt");
            FileWriter fw=new FileWriter("2.txt");
            int c=fr.read();
            while(c!=-1)
            {
                fw.write(c);
                c = fr.read(); // Add this line
            }
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
        finally
        {   
            fr.close();
            fw.close();
        }

    }
}
Fourinhand answered 2/5, 2013 at 5:36 Comment(0)
A
0

Check this javapractices you will get better idea. it will help u to understand more about try catch finally.

Arnica answered 2/5, 2013 at 5:38 Comment(0)
C
0
import java.io.*;
class FileDemo 
{
public static void main(String args[])throws IOException
{
    FileReader fr=null;
    FileWriter fw=null;
  try 
  {
      fr=new FileReader("1.txt");
      fw=new FileWriter("2.txt");
      int c=fr.read();
      while(c!=-1) 
      {
        fw.write(c);
      }
  } 
  catch(IOException e) 
  {
      System.out.println(e);
  } 
  finally
  { 
      fr.close();
      fw.close();
  }
}
}

1.your code is not correct > finally block does not takes parenthesis ahead if it. 2.parenthesis always comes in front of methods only. 3.dear your Scope of FileReader and FileWrier objects are end with in the try blocks so you will get one more error in finally block that is fw not found and fr not found 4."throws IOEXception" also mention front of main function

Crosscheck answered 27/6, 2013 at 20:26 Comment(0)
T
0
I see it is way old thread but writing it as many people still be using the above ways.
If you are using Java9 or above then I think, can look for below simple way -

       try(FileInputStream fis = new FileInputStream("e:/file1");
           FileOutputStream fos = new FileOutputStream("e:/file2");) { 
              fis.transferTo(fos);
         } catch(Exception e) { 
               e.printStackTrace(); 
         }

For me above code copied 2GB data in 50sec to new file.
If you need better performance then can check other ways.
Thunderous answered 10/8, 2020 at 11:50 Comment(0)
T
-1
public class Copytextfronanothertextfile{

    public static void main(String[] args) throws FileNotFoundException, IOException {

        FileReader fr = null;
        FileWriter fw = null;

        try{
        fr = new FileReader("C:\\Users\\Muzzammil\\Desktop\\chinese.txt");
        fw = new FileWriter("C:\\Users\\Muzzammil\\Desktop\\jago.txt");


        int c;
        while((c = fr.read()) != -1){
            fw.write(c);

        }


    }finally{

           if (fr != null){ 
            fr.close();
        }

           if(fw != null){

              fw.close();
           }
}

}

}
Toponym answered 20/8, 2016 at 19:21 Comment(0)
N
-2

Try this code:

class CopyContentFromToText {

    public static void main(String args[]){      

        String fileInput = "C://Users//Adhiraj//Desktop//temp.txt";
        String fileoutput = "C://Users//Adhiraj//Desktop//temp1.txt";
        try {
            FileReader fr=new FileReader(fileInput);
            FileWriter fw=new FileWriter(fileoutput);

            int c;
            while((c=fr.read())!=-1) {
                fw.write(c);
            } 
            fr.close();
            fw.close();

        } 
        catch(IOException e) {
            System.out.println(e);
        } 
     }
}
Naxos answered 30/5, 2015 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.