【问题标题】:error unreported exception when use BufferedInputStream使用 BufferedInputStream 时报错未报告异常
【发布时间】:2014-03-29 07:53:36
【问题描述】:

我正在尝试使用BufferedInputStream复制文件,编译时出现此错误:

BufferedByteStreamCopy2.java:22:错误:未报告的异常IOException;必须被抓住或宣布被扔掉 bin.close(); ^ BufferedByteStreamCopy2.java:24:错误:未报告的异常 IOException;必须被抓住或宣布被扔掉 回合.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();
 }

} }

【问题讨论】:

  • 您提供的代码编译得很好。鉴于您的公共类的名称和错误中报告的文件名,您确定这不仅仅是拥有两份源代码副本的问题 - 一份工作,一份损坏?

标签: java exception


【解决方案1】:

try/catch 将捕获异常,但这不适用于 finally 块中抛出的异常。您还需要尝试捕获其中的 close() 。

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

【讨论】:

  • 谢谢彼得!很抱歉造成混乱。这是使用 ButteredByteStreamCopy2Java 编辑的帖子。就像你说的那样,这是一个练习。虽然我真的不知道更有效的方法。
  • @user3474606 你第一次做对了,在异常处理程序中有一个 try/catch 块。考虑到您使用的是缓冲流,一次一个字节的问题并不重要,但还有其他 read() 方法。查找它们。
  • @PeterLawrey 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多