Copying the Contents of One text file to Another i

2019-03-27 16:37发布

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.

8条回答
Emotional °昔
2楼-- · 2019-03-27 17:07

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();
}
} 
查看更多
Luminary・发光体
3楼-- · 2019-03-27 17:12

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

查看更多
登录 后发表回答