【问题标题】:Copying the Contents of One text file to Another in Java在 Java 中将一个文本文件的内容复制到另一个文本文件
【发布时间】:2013-04-26 04:58:24
【问题描述】:

我正在尝试将包含 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() 中的 () 去掉。最后应该是 { }
  • 编译器消息是否不够清晰?上面写着“FileDemo.java:20: error: '{' expected”,并用箭头指向违规字符!当错误发生时,仔细阅读输出并思考其含义通常是值得的。

标签: java filereader filewriter


【解决方案1】:

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[]) 方法将完整内容复制到一个语句中(因此您的代码中不需要循环)。
【解决方案2】:

编译错误

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

    }

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:
        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函数的前面

        【讨论】:

          【解决方案6】:

          更有效的方法是......

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

          【讨论】:

            【解决方案7】:

            试试这个代码:

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

            【讨论】:

              【解决方案8】:
              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();
                         }
              }
              
              }
              
              }
              

              【讨论】:

                【解决方案9】:
                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.
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-02-07
                  • 2016-03-30
                  • 1970-01-01
                  相关资源
                  最近更新 更多