[英]File Read and Write
每當文本字段中有一個條目時,我都有一個用於寫入文件的代碼。 但是在此過程之后,當再次輸入條目時,文件將被重寫,而不是繼續輸入文件,因此我丟失了之前的數據。 我如何重寫現有數據,以便即使關閉應用程序后也可以讀取這些數據。
給出了寫過程的代碼:
public boolean writeToFile(String dataLine) {
dataLine = "\n" + dataLine;
try {
File outFile = new File(filepath);
dos = new DataOutputStream(new FileOutputStream(outFile));
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
任何人都可以根據需要對代碼進行更改並將其發布給我。
[FileOutputStream的Java API] [1]指出:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException)
創建輸出文件流以寫入具有指定名稱的文件。 如果第二個參數為true,則字節將被寫入文件的末尾而不是開頭。 創建一個新的FileDescriptor對象來表示此文件連接。
因此,您的代碼應如下所示:
public boolean writeToFile(String dataLine) {
dataLine = "\n" + dataLine;
try {
File outFile = new File(filepath);
dos = new DataOutputStream(new FileOutputStream(outFile,true));
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
[1]: http : //download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String ,boolean)
將構造函數FileOutputStream(File file, boolean append)
與append = true一起使用
參見[http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,boolean)] [1]
另請注意,您可能應該使用FileWriter編寫文本。 FileOutputStream用於二進制數據。
[1]: http : //download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File ,boolean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.