如何在java文本文件中编辑记录?

如何在java文本文件中编辑记录?,java,file-io,text-files,Java,File Io,Text Files,我有一个文本文件,其内容如下: 1 John 200 4 Jack 144 7 Sarah 123 Enter id of the record you want to edit? 1 New Name: Terry New Quantity: 700 1 Terry 700 4 Jack 144 7 Sarah 123 此记录的编程格式为 int id, String name, int quantity 我的问题是如何编辑这样

我有一个文本文件,其内容如下:

    1 John 200
    4 Jack 144
    7 Sarah 123
Enter id of the record you want to edit?
1
New Name:
Terry
New Quantity:
700
    1 Terry 700
    4 Jack 144
    7 Sarah 123
此记录的编程格式为

     int id, String name, int quantity
我的问题是如何编辑这样的记录:

    1 John 200
    4 Jack 144
    7 Sarah 123
Enter id of the record you want to edit?
1
New Name:
Terry
New Quantity:
700
    1 Terry 700
    4 Jack 144
    7 Sarah 123
因此,执行此操作后,文件必须如下所示:

    1 John 200
    4 Jack 144
    7 Sarah 123
Enter id of the record you want to edit?
1
New Name:
Terry
New Quantity:
700
    1 Terry 700
    4 Jack 144
    7 Sarah 123

但是我还是一个java初学者,所以我被困在这段代码中?

这是您的代码。如果你需要解释,请告诉我:D

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ScanFile {
    public static void main(String[] args)throws IOException {

        String newName=null;
        String newQuantity=null;
        boolean checked = true;

     File f= new File("E:\\myFile.txt");          // path to your file
     File tempFile = new File("E:\\myTempFile.txt"); // create a temp file in same path
     BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
     Scanner sc = new Scanner(f);
     System.out.println("Enter id of the record you want to edit?");
     Scanner sc2 = new Scanner(System.in);
     int id = sc2.nextInt();
     while(sc.hasNextLine())
     {
         String currentLine= sc.nextLine();
         String[] tokens = currentLine.split(" ");
         if(Integer.valueOf(tokens[0])==id && checked)
         {
             sc2.nextLine();                          
             System.out.println("New Name:");
             newName= sc2.nextLine();
             System.out.println("New Quantity:");
             newQuantity= sc2.nextLine();
             currentLine = tokens[0]+" "+newName+" "+newQuantity;
             checked = false;
         }
         writer.write(currentLine + System.getProperty("line.separator"));

     }
     writer.close(); 
     sc.close();
     f.delete();
     boolean successful = tempFile.renameTo(f);

    }
}

阅读你的文件。为每行创建一个新对象,然后将其存储在列表或其他内容中。编辑对象并写回所有内容。如果文件不太大,最简单的方法是将其完全读取到内存列表中。您可以使用扫描仪或类似设备。然后修改列表并再次写出。@初学者程序员您应该选择另一个昵称:“初学者经理”。程序员自己编写程序。请求帮助是可以的,但是如果你想要的只是有人为你做这项工作,那就不再是编程了。投票结束。好吧,我很抱歉你可以结束这个问题:(为他人完成家庭作业既浪费你的时间,也浪费他们的时间,而且违背了Stack Overflow帮助用户自己找到答案的原则。好的。我会从现在起记住这一点。谢谢。