我尝试在try-catch
块中传入一个文本文件(输入和输出文件)作为命令行参数。
这是代码的一小段:
try {
PrintWriter outFile = new PrintWriter(new FileOutputStream(args[0]));
} catch (FileNotFoundException exc) {
System.out.println("file does not exist");
} catch (Exception e) {
System.out.println("general exception");
}
我试图通过传递一个不存在的文件来检查它,但它似乎不起作用,甚至在一般的异常中也不起作用。我也尝试过printStream
,但是什么都没有改变。
如有任何帮助,将不胜感激,谢谢!
发布于 2016-09-19 16:19:50
首先从文本创建文件
File inputFile = new File(args[0]);
现在使用inputFile.exists()
检查文件是否存在,如果文件存在,则返回boolean
结果true
;如果文件不存在,则返回false
此外,您还希望检查目录,因为如果输入路径是目录(文件夹),inputFile.exists()
也会返回true
所以你的支票看起来就像
if(inputFile.exists() && ! inputFile.isDirectory()) // ! mean not/complement operator
{
// yes it's a file
}
为什么要补充?因为我们只想在输入表示文件而不是目录的情况下走得更远
https://stackoverflow.com/questions/39577611
复制