我目前正在處理將文件內容轉換爲字符串的簡單方法。我看到幾個主題涵蓋了這個問題的一些細節(here)。不過,我可以使用前面鏈接答案中提到的try catch或return do_nothing。代碼:
這是避免空值返回的好方法嗎?
public static String getStringFromFile(String path) throws EmptyFileException {
String data =null;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
while ((line = reader.readLine()) != null) {
data += line +"\n";
}
if (data == null) {
throw new EmptyFileException();
}
}
catch (FileNotFoundException ex) {
showExceptionMessage("File not found");
}
catch (IOException ex) {
showExceptionMessage("Can't read the file");
}
return(data);
}
private static void showExceptionMessage(String message) {
JOptionPane.showMessageDialog(null, message, "ERROR", JOptionPane.ERROR_MESSAGE);
}
那麼,什麼是「更好」拋出一個異常,如果該文件是空的或只使用返回doNothing()(分別爲doNothing是什麼也不做的功能,是有道理的右HAHAH?)。
從應用程序的角度來看,處理缺少的文件,空文件和錯誤讀取可以作爲一般「無信息發現」情況那會導致「無所事事」的流程?或者換一種說法,如果在文件中找到它,你是否只想顯示一條消息,否則不顯示任何內容(即使輸入錯誤來從文件中獲取消息)? – Bohemian