簡體   English   中英

如何在Java中的txt文件中寫入特定的行號

[英]How can I write to a specific line number in a txt file in Java

我正在寫我的學校項目,其中要求我讀取和寫入txt文件。 我可以正確讀取它們但我只能在附加的FileWriter中寫入它們。 我希望能夠通過首先刪除行上的數據然后寫入新數據來覆蓋行號上的txt文件中的內容。 我試圖使用這種方法......

public void overWriteFile(String dataType, String newData) throws IOException
{
    ReadFile file = new ReadFile(path);
    RandomAccessFile ra = new RandomAccessFile(path, "rw");
    int line = file.lineNumber(path, dataType);
    ra.seek(line);
    ra.writeUTF(dataType.toUpperCase() + ":" + newData);
}

但我相信搜索方法以字節而不是行號移動。 誰能幫忙。 提前致謝 :)

PS file.lineNumber方法返回舊數據所在的確切行,因此我已經有了需要寫入的行號。

編輯:Soloution發現! 謝謝大家:)如果有人有興趣,我會在下面發布soloution

public void overWriteFile(String dataType, String newData, Team team, int dataOrder) throws IOException
{
    try
    {
        ReadFile fileRead = new ReadFile(path);
        String data = "";
        if(path == "res/metadata.txt")
        {
            data = fileRead.getMetaData(dataType);
        }
        else if(path == "res/squads.txt")
        {
            data = fileRead.getSquadData(dataType, dataOrder);
        }
        else if(path == "res/users.txt")
        {
            data = fileRead.getUsernameData(dataType, dataOrder);
        }
        else if(path == ("res/playerdata/" + team.teamname + ".txt"))
        {
            //data = fileRead.getPlayerData(dataType, team.teamname, dataOrder);
        }
        BufferedReader file = new BufferedReader(new FileReader(path));
        String line;
        String input = "";
        while((line = file.readLine()) != null)
        {
            input += line + '\n';
        }
        input = input.replace(dataType.toUpperCase() + ":" + data, dataType.toUpperCase() + ":" + newData);
        FileOutputStream out = new FileOutputStream(path);
        out.write(input.getBytes());
    }
    catch(Exception e)
    {
        System.out.println("Error overwriting file: " + path);
        e.printStackTrace();
    }
}

一個快速而又臟的解決方案是使用Files.readAllLinesFiles.write方法讀取所有行,更改要更改的行,並覆蓋整個文件:

List<String> lines = Files.readAllLines(file.toPath());
lines.set(line, dataType.toUpperCase() + ":" + newData);
Files.write(file.toPath(), lines); // You can add a charset and other options too

當然,如果它是一個非常大的文件,這不是一個好主意。 有關如何在這種情況下逐行復制文件的一些想法,請參閱此答案

但是,無論您如何操作,如果要更改行的字節長度,都需要重寫整個文件(AFAIK)。 RandomAcessFile允許您移動文件並覆蓋數據,但不插入新字節或刪除現有字節,因此文件的長度(以字節為單位)將保持不變。

這里有一個問題的鏈接就像這樣一個很好的答案: 我想打開一個文本文件並在java中編輯一個特定的行

基本上,你不能只編輯那一行,除非它的長度完全相同。

相反,您需要復制每一行,然后當您到達要更改的行的行號時,而不是復制舊行,只需放入新行。

我給你的鏈接有一個很好的例子來說明如何做到這一點。

我希望這有幫助......如果沒有,請告訴我,我會在帖子上進一步闡述。 祝好運 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM