簡體   English   中英

重寫txt文件中的特定行

[英]Rewrite a specific line in a txt file

我正在嘗試重寫txt文件中包含學生詳細信息的行。 文件中將列出學生的詳細信息,例如:

  • 名稱1,10
  • 名稱2,20
  • 名稱3,30

我試圖使用BufferedReader將Name2,20重寫為Name2,13,以查找具有Name2的行。 還有一個BufferedWriter用新文本替換該行,但事實證明代碼會將我的整個txt文件寫為null。

這是我的代碼:

String lineText;
String newLine = "Name,age";
    try {
        BufferedReader br = new BufferedReader(new FileReader(path));
        BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
        while ((lineText = br.readLine()) != null){
             System.out.println(">" + lineText);
            String studentData[] = lineText.split(",");
            if(studentData[0].equals(Name2)){
                bw.write(newLine);
            }
            System.out.println(lineText);
        }
        br.close();
        bw.close();

        }
        catch (IOException e) {
            e.printStackTrace();
        }

誰能告訴我如何在txt文件中重寫特定行?

最簡單的方法是讀取整個文件,並將其存儲在變量中。 讀取當前文件時替換有問題的行。

就像是:

String lineText;
String newLine = "Name,age";
try {
    BufferedReader br = new BufferedReader(new FileReader(path));
    BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
    String currentFileContents = "";
    while ((lineText = br.readLine()) != null){
        System.out.println(">" + lineText);
        String studentData[] = lineText.split(",");
        if(studentData[0].equals("Name2")){
            currentFileContents += newLine;
        } else {
            currentFileContents += lineText;
        }
    }

    bw.write(currentFileContents);
    br.close();
    bw.close();

} catch (IOException e) {
    e.printStackTrace();
}

暫無
暫無

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

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