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

时间:2015-10-24 18:32:34

标签: java file-io text-files

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

    1 John 200
    4 Jack 144
    7 Sarah 123

此记录的编程格式为

     int id, String name, int quantity

我的问题是如何编辑这样的记录:

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初学者?

1 个答案:

答案 0 :(得分:0)

这是你的代码。如果您需要解释,请告诉我: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);

    }
}