我試圖打開並閱讀從命令行傳遞的文件。(java)
這是我到目前爲止有:
import java.io.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
if ((args[0].length() == 0) || (args[0] == null) || (args[0].isEmpty())) {
System.err.println("Usage Error: No file name was provided.");
System.exit(1);
}
File file = new File(args[0]);
if (!file.exists()) {
System.err.println("Usage Error: The file, " + args[0] + ", does not exist.");
}
if (!file.canRead()) {
System.err.println("Usage Error: The file, " + args[0] + ", cannot be read.");
}
} // main
}
我不完全相信我應該如何處理文件沒有發現異常。我的老師提到了try/catch塊,但我不確定我是否需要這些。僅僅測試一下文件是否作爲參數傳遞是否足夠,並且它是否使用System.err.print()方法給用戶一個錯誤?另外,如果System.err.print()被調用,它會在那之後退出程序(也就是說,在那之後是否需要包含System.exit(1))?或者是更好的(在設計方面),只是做這樣的事情:
public void readFile() throws FileNotFoundException {
// try to open file here
}
public static void main(String[] args) {
try {
readFile();
} catch (Exception e) {
// exception handled here
}
}
我只是需要確保用戶實際上通過一個字符串作爲文件名,它的存在/可以被讀取。
不同之處在於它們不一樣。一個打印輸出到控制檯。另一個改變程序流程。這全部記錄在案。沒有必要猜測。 – EJP