确定打开两个文件时无法找到的文件

时间:2016-02-26 23:27:43

标签: java

有没有办法可以打印出我们在这种情况下无法找到的文件?

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)

但我只对文件名感兴趣,而不是整个字符串。

3 个答案:

答案 0 :(得分: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 :(得分: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);
    }

答案 2 :(得分:1)

如果你有一个文件名数组,你可以做这样的事情

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