Java 使用BufferedInputStream时出现错误未报告异常
我正在尝试使用Java 使用BufferedInputStream时出现错误未报告异常,java,exception,Java,Exception,我正在尝试使用BufferedInputStream复制文件,编译时发生此错误: java:22:错误:未报告的异常IOException;必须被抓住或宣布被抛出 bin.close(); ^ java:24:错误:未报告的异常IOException;必须被抓住或宣布被抛出 about.close(); ^ 你能帮我解释一下吗?如何修改代码?非常感谢 import java.io.*; public class BufferedByteStreamCopy2 { public static
BufferedInputStream
复制文件,编译时发生此错误:
java:22:错误:未报告的异常IOException;必须被抓住或宣布被抛出
bin.close();
^
java:24:错误:未报告的异常IOException;必须被抓住或宣布被抛出
about.close();
^
你能帮我解释一下吗?如何修改代码?非常感谢
import java.io.*;
public class BufferedByteStreamCopy2 {
public static void main(String[] args) {
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
FileInputStream fin = new FileInputStream(args[0]);
bin = new BufferedInputStream(fin);
FileOutputStream fout = new FileOutputStream(args[1]);
bout = new BufferedOutputStream(fout);
int c;
while ((c = bin.read()) != -1)
bout.write(c);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Not enough parameter.");
} catch (FileNotFoundException e) {
System.out.println("Could not open the file:" + args[0]);
} catch (Exception e) {
System.out.println("ERROR copying file");
} finally {
if (bin != null)
bin.close();
if (bout != null)
bout.close();
}
}
}try/catch将捕获异常,但这不适用于finally块中抛出的异常。这里的close()也需要一个try catch
注意:一次复制一个字节效率很低,我想这只是一个练习。正如@EJP指出的,还有更多的read()和write()方法。您提供的代码编译得很好。考虑到您的公共类的名称和错误中报告的文件名,您确定这不仅仅是源代码的两个副本(一个工作,一个损坏)的问题吗?谢谢Peter!很抱歉造成混淆。这是用ButteredByTestStreamCopy2Java编辑的帖子。就像你说的,这是一种锻炼。虽然我真的不知道一种更有效的方法。@user3474606您第一次做对了,在异常处理程序中有一个try/catch块。考虑到您使用的是缓冲流,一次一个字节的问题并不严重,但是还有其他read()方法。查一下。@PeterLawrey非常感谢!