【问题标题】:checking files as command line arguments in java在java中检查文件作为命令行参数
【发布时间】:2016-09-20 01:48:47
【问题描述】:

我正在尝试将文本文件(输入和输出文件)作为try-catch 块内的命令行参数传递。

这是一个sn-p的代码:

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,但没有真正改变。

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

【问题讨论】:

  • 根据FileOutputStream JavaDoc, FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason. 也许你传入的文件CAN被创建了,所以它正在为你创建它。也许让目录只读,看看它是否仍然有效。

标签: java eclipse command-line-arguments


【解决方案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
 }

为什么要补?因为我们只想在输入代表文件而不是目录时更进一步

【讨论】:

    猜你喜欢
    • 2010-09-16
    • 1970-01-01
    • 2015-09-12
    • 2011-04-21
    • 2013-10-17
    • 2017-03-10
    • 2011-06-24
    • 2012-09-24
    • 2012-12-21
    相关资源
    最近更新 更多