在Java中将一个文本文件的内容复制到另一个文本文件 [英] Copying the Contents of One text file to Another in Java

查看:139
本文介绍了在Java中将一个文本文件的内容复制到另一个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

命令提示符: -

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

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

推荐答案

它是最后,而不是 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();
}

finally 阻止,您的 fr fw 变量无法找到,因为它们是在<$范围内声明的c $ c>尝试阻止。在外面声明它们:

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

现在,因为它们已初始化使用 null 值,您还必须在关闭它们之前执行 null 检查:

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

关闭方法都可以抛出必须处理的 IOException

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

最后,由于您不希望有大量代码来关闭基本流,只需将其移动到处理 可关闭 (请注意, FileReader FileWriter 都实现了此接口):

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

从Java 7开始,我们有 try-with-resources ,因此可以重写上面的代码喜欢:

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

这篇关于在Java中将一个文本文件的内容复制到另一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆