Java中将一个文本文件的内容复制到另一个文件

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()块已经正确关闭。


移除 finally() 中的括号。应该写成 finally { }。 - Dev Blanked
编译器的信息不够清晰吗?它说:“FileDemo.java:20:error:'{'expected”,并在有问题的字符处指出一个箭头!当发生错误时,通常要仔细阅读输出并思考其含义。 - Adriaan Koster
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 块中,你的 frfw 变量无法找到,因为它们是在 try 块的范围内声明的。请在外部声明:

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

最后,由于您不想有很多代码来关闭基本流,所以只需将其移入处理Closeable的方法中(请注意,FileReaderFileWriter都实现了此接口):
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();
        }
    }
}

很棒的答案!我经常看到的读取循环的习惯用语是:int c; while((c = fr.read()) != -1) { fw.write(c); } 虽然不一定更易读,但可以节省一行代码。您还可以使用read(char[])和write(char[])方法在一个语句中复制完整内容(因此您的代码中不需要循环)。 - Adriaan Koster

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

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.括号只能出现在方法的前面。 3.亲爱的,你的FileReader和FileWriter对象的作用域在try块中结束,所以你会在finally块中得到一个更多的错误,即fw未找到和fr未找到。 4.在主函数前也要注明“throws IOEXception”。


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

    }

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

    }
}

0

看看这个javapractices,你会有更好的理解。 它将帮助你更好地了解try catch finally。


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.

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

}

}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接