首页 文章

使用BufferedInputStream时出现错误未报告的异常

提问于
浏览
0

我试图使用 BufferedInputStream 复制文件,并在编译时发生此错误:

BufferedByteStreamCopy2.java:22:错误:未报告的异常IOException;必须被捕获或声明被抛出bin.close(); ^ BufferedByteStreamCopy2.java:24:错误:未报告的异常IOException;必须被 grab 或宣布被抛出bout.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();
 }

}}

1 回答

  • 0

    try / catch将捕获异常,但这不适用于finally块中抛出的异常 . 你也需要在close()中尝试catch .

    注意:一次复制一个字节是非常低效的,我认为这只是一个练习 . 正如@EJP指出的那样,有更多的read()和write()方法 .

相关问题