2017-06-12 189 views
1

我正在編寫一個簡單的終端程序,記錄一些信息,並將其放入一個文本文件中,稍後有人可以回憶。主要是爲了記錄他所做的事情。我在窗戶上很好,並沒有真正遇到這個問題,但我擔心我正在尋找簡單的東西。Linux和java:正在創建文件,但文本沒有寫入

就像我之前說的,如果我瀏覽到該項目目錄,我看到文件已經創建,但是當我打開使用文本編輯器文件,打印沒有創建的字符串中的數據。

private static void writeFile(String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{ 
    File fileName = new File("log.txt"); 
    FileOutputStream fos; 
    try { 
     fos = new FileOutputStream(fileName); 
     BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos)); 
     int i =0; 
     write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n"); 
     i++; 
     System.out.println("File has been updated!"); 
    } catch (FileNotFoundException ex) { 
     Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 
+0

無關你的問題,但變量'fileName'是一種嚴重命名。它是實際的'File'對象,而不是文件*名稱*。 –

+0

哈哈很好,謝謝! – user3026473

+0

是否因爲您需要關閉BufferedWriter和FileOutputStream以確保所有內容都寫入文件? –

回答

0

BufferedWriter類調​​用write()功能後,你需要調用close()功能。您還應該在FileOutputStream對象上調用close()函數。

所以,你的新代碼應該是這樣的:

private static void writeFile(String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{ 
File fileName = new File("log.txt"); 
FileOutputStream fos; 
try { 
    fos = new FileOutputStream(fileName); 
    BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos)); 
    int i =0; 
    write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n"); 

    // Close your Writer 
    write.close(); 

    // Close your OutputStream 
    fos.close(); 

    i++; 
    System.out.println("File has been updated!"); 
} catch (FileNotFoundException ex) { 
    Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex); 
} 

} 
+1

在'close'完全沒有必要之前調用'flush','flush'應該只有當我們想寫某些東西時纔會使用,但我們仍然希望讓文件處理,以便稍後寫入它(例如套接字編程) – niceman

+0

以關閉封裝流,然後關閉底層流,再次不需要(所以'write.close'已經足夠了,不需要'fos.close()') – niceman

+0

我不好,我會編輯我的答案以省略flush()。 – AMFTech

1

您需要關閉輸出,或者更確切地說,是你需要的代碼,以便它將被關閉(不一定關閉它明確)。 Java 7引入了完全處理這種情況的try with resources語法。

的任何對象,它是AutoCloseable可以自動,安全地使用這種語法,這樣關閉:

private static void writeFile(String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{ 
    File fileName = new File("log.txt"); 
    try (FileOutputStream fos = = new FileOutputStream(fileName); 
     BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));) { 
     int i =0; 
     write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n"); 
     i++; 
     System.out.println("File has been updated!"); 
    } catch (FileNotFoundException ex) { 
     Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

只需將您可關閉對象的初始化到try資源塊將確保它們是關閉,這將作爲關閉後果的flush()