我試圖創建一個文件,如果它不存在,如果它確實存在追加到它。 這是最好的辦法嗎?我不確定在一種方法中有兩次嘗試捕獲是否有益於個人?Java IO創建/追加文件
public static void main(String [] args)
{
String fileLocation = "/temp/";
String name = "Bob";
String timeStamp = "1988-03-15";
Path path = Paths.get(fileLocation+ "info.log");
if(!Files.exists(path)){
try {
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
SimpleDateFormat tTimeFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
writer.write(tTimeFormatter.format(System.currentTimeMillis()) + " name: " + name + " Timestamp: "+ timeStamp);
writer.newLine();
} catch (IOException e) {
System.out.print(e.getStackTrace());
}
}
這裏有什麼問題? –
什麼是檢查文件是否存在的最好方法,如果不存在則創建它,如果存在則附加到文件。 –
這裏有一個邏輯問題,如果文件不存在並且創建失敗,它仍會嘗試寫入文件,從而導致另一個異常。 – npinti