7

我正在尝试将包含 2-3 个整数(例如:1 2 3)的一个文本文件(“1.txt”)的内容复制到另一个文本文件(“2.txt”),但出现以下错误编译时

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();
      }
    }
}

命令提示符:-

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

但是在检查代码后,我发现 finally() 块已正确关闭。

4

9 回答 9

30

它是finally,不是finally()

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

顺便说一句,你有一个无限循环:

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

您必须读取循环内的数据才能让它完成:

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

finally块中,找不到您的fr和变量,因为它们是在块的范围内声明的。在外面声明它们:fwtry

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

现在,由于它们是用null值初始化的,因此您还必须null在关闭它们之前进行检查:

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

并且close两者上的方法都可以抛出IOException必须处理的问题:

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

最后,由于您不希望有很多代码来关闭基本流,只需将其移动到处理 a 的方法中Closeable(注意两者都FileReader实现FileWriter了这个接口):

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

最后,您的代码应如下所示:

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) {
            //...
        }
    }
}

从 Java 7 开始,我们有了try-with-resources,所以上面的代码可以重写为:

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();
        }
    }
}
于 2013-05-02T05:32:15.173 回答
4

更有效的方法是...

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();
}
} 
于 2014-10-03T07:50:18.673 回答
0

块不应该有Finally圆括号。

尝试:

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();
        }

    }
}
于 2013-05-02T05:36:17.410 回答
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.你的代码不正确 > finally 块如果它不带括号。2.parenthesis 总是只出现在方法的前面。3.亲爱的,你的 FileReader 和 FileWrier 对象的范围在 try 块中结束,所以你会在 finally 块中得到另一个错误,即 fw not found 和 fr not found 4.“throws IOEXception”还提到了 main 函数的前面

于 2013-06-27T20:26:18.860 回答
0

检查这个javapractices你会得到更好的主意。它将帮助您最终了解有关 try catch 的更多信息。

于 2013-05-02T05:38:00.137 回答
0

它是一个编译错误

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();
        }

    }
于 2013-05-02T05:32:33.653 回答
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.
于 2020-08-10T11:50:05.223 回答
-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();
           }
}

}

}
于 2016-08-20T19:21:43.337 回答
-2

试试这个代码:

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);
        } 
     }
}
于 2015-05-30T17:28:40.020 回答