我有一個 .txt 檔案將被許多用戶訪問,可能同時(或接近),因此我需要一種方法來修改該 txt 檔案而不創建臨時檔案,我還沒有找到答案或解決這個問題。到目前為止,我只找到了這種方法->
獲取現有檔案->修改某些內容->將其寫入新檔案(臨時檔案)->洗掉舊檔案。
但是他的方法對我不好,我需要類似的東西:獲取現有檔案->修改它->保存。
這可能嗎?如果這個問題已經存在,我真的很抱歉,我嘗試搜索 Stack-overflow 并通過 Oracle Docs 閱讀,但我沒有找到適合我需要的解決方案。
編輯:
修改后,檔案將保持與以前相同的大小。例如想象學生串列,每個學生的值可以是 1 或 0(通過或未通過考試)
所以在這種情況下,我只需要更新檔案中的每行一個字符(即每個學生)。例子:
李·杰克遜 0 -> 李·杰克遜 0
Bob White 0 -> 會變成 -> Bob White 1
杰西卡吳 1 -> 杰西卡吳 1
在上面的示例中,我們有一個檔案,其中有 3 條記錄,一條在另一條之下,我需要更新第二條記錄,而第一條和第三條記錄將變得相同,并且所有這些都無需創建新檔案。
uj5u.com熱心網友回復:
這是一種使用RandomAccessFile. 這個想法是用readline字串讀取它,但要記住檔案中的位置,這樣你就可以回到那里寫一個新行。如果文本編碼中的任何內容會改變位元組長度,這仍然是有風險的,因為這可能會覆寫換行符。
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();
}
}
}
在這種情況下,處理正確的字串編碼是很棘手的。如果檔案不在 and 使用的編碼中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"));
請參閱如何使用 RandomAccessFile 讀取 UTF8 編碼檔案?
uj5u.com熱心網友回復:
嘗試將您想要對檔案進行的更改存盤在 RAM 中(字串或字串的鏈接串列)。如果您將檔案讀入字串的鏈接串列(檔案的每行)并撰寫一個函式以將要插入的字串合并到檔案中的該行的鏈接串列中,然后通過放下每個鏈表中的行它應該給你你想要的。這就是我在 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]...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511800.html
標籤:爪哇文件
上一篇:包含不同檔案路徑的檔案
下一篇:從檔案中加載包含單詞的字串
