2015-10-24 37 views
-2

我有有内容像这样的文本文件:如何编辑java文本文件中的记录?

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

发表您的代码.. – Satya

+0

阅读您的文件。为每一行创建一个新对象,然后将其存储在一个List或其他东西中。编辑对象并将所有内容写回。 –

+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); 

    } 
} 
+0

为他们完成他人的家庭作业既浪费你的时间和他们的时间,也违反Stack Overflow的原则**协助**用户自己找到答案** **。 –

+0

好的。我从现在开始记住这一点,谢谢。 –