简体   繁体   中英

Rewrite a specific line in a txt file

I was trying to rewrite a line that contains student details in a txt file. There will be a list of students' detail in the file, for example:

  • Name1,10
  • Name2,20
  • Name3,30

I tried to rewrite Name2,20 to Name2,13 using a BufferedReader to find the line with Name2. And a BufferedWriter to replace the line with new text, but it turns out the code will write my whole txt file to null.

Here's my code:

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();
        }

Can anyone please tell me how to rewrite a specific line in txt file?

Easiest way is to read the entire file, and store it in a variable. Replacing the line in question while reading the current file.

Something like:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM