[英]error unreported exception when use BufferedInputStream
我正在嘗試使用BufferedInputStream
復制文件,並且在編譯時發生此錯誤:
BufferedByteStreamCopy2.java:22:錯誤:未報告的異常IOException; 必須被捕獲或聲明為引發bin.close(); ^ BufferedByteStreamCopy2.java:24:錯誤:未報告的異常IOException; 必須被捕獲或聲明為被拋出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();
}
}}
try / catch將捕獲異常,但這不適用於在finally塊中引發的異常。 您還需要在其中的close()嘗試捕獲。
注意:一次復制一個字節效率很低,我認為這只是一個練習。 正如@EJP指出的那樣,還有更多的read()和write()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.