[英]Modifying txt file in Java without creating temp file
我有一個 .txt 文件,許多用戶可能同時(或接近)訪問,因此我需要一種方法來修改該 txt 文件而不創建臨時文件,但我沒有找到答案或解決這個問題。 到目前為止,我只找到了這種方法->
獲取現有文件 -> 修改某些內容 -> 將其寫入新文件(臨時文件) -> 刪除舊文件。
但是他的方法對我不好,我需要這樣的東西:獲取現有文件 -> 修改它 -> 保存它。
這可能嗎? 如果這個問題已經存在,我真的很抱歉,我嘗試搜索 Stack-overflow 並閱讀了 Oracle 文檔,但我沒有找到適合我需要的解決方案。
編輯:
修改后,文件將保持與以前相同的大小。 例如想象學生列表,每個學生可以有值 1 或 0(通過或未通過考試)
所以在這種情況下,我只需要更新文件中每行的一個字符(即每個學生)。 例子:
李 Jackson 0 -> 李 Jackson 0
Bob White 0 -> 會變成 -> Bob White 1
傑西卡吳 1 -> 傑西卡吳 1
在上面的示例中,我們有一個包含 3 條記錄的文件,我需要更新第 2 條記錄,而第 1 條和第 3 條記錄將變得相同,而無需創建新文件。
這是使用RandomAccessFile
的潛在方法。 這個想法是使用readline
以字符串形式讀取它,但要記住文件中的 position,這樣你就可以 go 回到那里並寫一個新行。 如果文本編碼中的任何內容會改變字節長度,這仍然是有風險的,因為這可能會覆蓋例如換行符。
void modifyFile(String file) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
long beforeLine = raf.getFilePointer();
String line;
while ((line = raf.readLine()) != null) {
// edit the line while keeping its length identical
if (line.endsWith("0")) {
line = line.substring(0, line.length() - 1) + "1";
}
// go back to the beginning of the line
raf.seek(beforeLine);
// overwrite the bytes of that line
raf.write(line.getBytes());
// advance past the line break
String ignored = raf.readLine();
// and remember that position again
beforeLine = raf.getFilePointer();
}
}
}
在這種情況下處理正確的 String 編碼是很棘手的。 如果文件不在readline()
和getBytes()
使用的編碼中,您可以通過執行
// file is in "iso-1234" encoding which is made up.
// reinterpret the byte as the correct encoding first
line = new String(line.getBytes("ISO-8859-1"), "iso-1234");
... modify line
// when writing use the expected encoding
raf.write(line.getBytes("iso-1234"));
嘗試將要對文件所做的更改存儲在 RAM 中(字符串或字符串鏈表)。 如果您在文件中讀入一個字符串鏈表(文件的每一行)並編寫一個 function 以將要插入的字符串從文件中合並到該行鏈表中,然后通過放下每個行來完全重寫文件鏈表中的行它應該給你你想要的。 這就是我在 psudocode 中的意思,順序在這里很重要。 通過讀取文件並在輸入后進行設置,我們可以最大限度地減少對其他用戶的干擾。
String lineYouWantToWrite = yourInput
LinkedList<String> list = new LinkedList<String>()
while (file has another line)
list.add(file's next line)
add your string to whatever index of list you want
write list to file line by line, file's first line = list[1]...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.