在java中将文件作为命令行参数进行检查

时间:2016-09-19 16:14:11

标签: java eclipse command-line-arguments

我试图将文本文件(输入和输出文件)作为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,但没有真正改变。

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

首先从文本

创建文件
   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
 }

为什么补充?因为如果输入表示文件而非目录

,我们只想更进一步
相关问题