[英]checking files as command line arguments in java
我正在嘗試將文本文件(輸入和輸出文件)作為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
,但是什么都沒有真正改變。
任何幫助,將不勝感激,謝謝!
首先從文本創建文件
File inputFile = new File(args[0]);
現在使用inputFile.exists()
檢查文件是否存在,如果文件存在,則boolean
將為true
否則,則為false
另外,您還要檢查目錄,因為如果輸入Path是目錄(文件夾),則inputFile.exists()
也會返回true
所以你的支票看起來像
if(inputFile.exists() && ! inputFile.isDirectory()) // ! mean not/complement operator
{
// yes it's a file
}
為什么要補充? 因為我們只想在輸入代表文件而不是目錄時走得更遠
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.