2016-02-26 63 views
0

有沒有一種方法可以打印出我們在這種情況下無法找到的文件?確定打開兩個文件時我們找不到哪個文件

try{ 
     in1 = new Scanner(new File(inPath1)); 
     in2 = new Scanner(new File(inPath2)); 
} catch (FileNotFoundException e){ 
     System.err.println("File not found: " e); 
     System.exit(0); 
} 

此打印出:

File not found: java.io.FileNotFoundException: test.dat (The system cannot find the file specified) 

但我只在文件名,而不是整個字符串感興趣。

+0

你可以把它分成兩個單獨嘗試捕獲 – dbrown93

+0

@ dbrown93是的,這是我的最後一招,但必須有一個更優雅的解決方案。 –

回答

2

呀稍作更改您的代碼如下:

String path = null; //track file name 
try{ 
     in1 = new Scanner(new File(path = inPath1)); 
     in2 = new Scanner(new File(path = inPath2)); 
} catch (FileNotFoundException e){ 
     System.err.println("File not found: " + path);//get recent file name 
     System.exit(0); 
} 
1

是的,那是可能的。你可以通過解析異常消息來完成。在這裏,我用空間分隔符來區分文件名和其他異常信息,所以我不希望文件中有空格。

try{ 
     in1 = new Scanner(new File(inPath1)); 
     in2 = new Scanner(new File(inPath2)); 
    } catch (FileNotFoundException e){ 
     String message = e.getMessage(); 
     int i = message.indexOf(" "); 
     String fileName = message.substring(0, i).trim(); 
     System.err.println("File not found: " + fileName); 
     System.exit(0); 
    } 
1

如果你有文件名的數組,你可以做這樣的事情

for(String s : a){ 
    try{ 
     files.add(new File(s)); 
    } catch (FileNotFoundException e){ 
     System.err.println("File not found: " + s); 
    } 
} 
相關問題