2016-01-21 65 views
0

我試圖創建一個文件,如果它不存在,如果它確實存在追加到它。 這是最好的辦法嗎?我不確定在一種方法中有兩次嘗試捕獲是否有益於個人?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()); 
     } 
    } 
+0

這裏有什麼問題? –

+0

什麼是檢查文件是否存在的最好方法,如果不存在則創建它,如果存在則附加到文件。 –

+0

這裏有一個邏輯問題,如果文件不存在並且創建失敗,它仍會嘗試寫入文件,從而導致另一個異常。 – npinti

回答

2

您可以使用StandardOpenOptions寫入文件:CREATE和APPEND。

Files.write(Paths.get(""), new byte[] {}, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

CREATE - 表示如果文件不存在,則會創建新的文件,否則會生成新文件。 APPEND - 表示將新數據附加到文件中的現有內容。

所以,你可以用一條線來完成所有的操作。

+0

Ohh非常好 - 我不知道我可以在多個選項中創建和追加在一起工作。 –

+0

是的,最好使用Files類來處理文件。 – eg04lt3r

+0

另外,如果我想要一個新的行ID需要做Files.write(路徑,「新行」,選項); –

0

嘗試使用的PrintWriter類這樣

java.io.PrintWriter p = new java.io.PrintWriter(yourFileHere); 
// You can use println to print a new line if it allready exists 
p.println(yourTextHere); 
// Or append to the end of the file 
p.append("TEXT HERE!!!!") 
0

的File.createNewFile()方法創建此抽象路徑名命名的,當且僅當這個名稱的文件尚不存在的新的空文件。如果文件已成功創建,則此方法返回一個真值,如果文件已存在或操作失敗,則返回false。

if (myFile.createNewFile()){ 
    System.out.println("File is created!"); 
    }else{ 
    System.out.println("File already exists."); 
    }