如何更新.txt文件中的包含java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16383578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:36:32  来源:igfitidea点击:

how to update the contain in .txt file java

javafiletextfile-ioio

提问by surisava

for example i have the file named file.txtwhich contain personal information (id,name, salary):

例如,我有一个名为的文件file.txt,其中包含个人信息(id、name、salary):

A123 Anna 3000
A234 Alex 4000
A986 Jame 5000

How can I write a java code that allow user to enter an ID of a person and replenish salary? The final output will look like:

如何编写允许用户输入人员ID并补充工资的Java代码?最终输出将如下所示:

Enter ID: A123

输入编号:A123

Enter replenish salary: 2000

输入补薪:2000

file.txt after run the program:

运行程序后的file.txt:

A123 Anna 5000
A234 Alex 4000
A986 Jame 5000

This is what i have done so far but it didnt work:

这是我到目前为止所做的,但没有奏效:

public static void addDalary() throws IOException {
        String ID, Nanme;
        double salary;


            Scanner console = new Scanner(System.in);
            System.out.print("Enter ID : ");
            String pID = console.nextLine();
            System.out.print("Enter replenish salary: ");
            replenish = console.nextInt();

            Scanner input = new Scanner(new File("file.txt"));
            while (input.hasNext()) {
                ID = input.next();
                Name = input.next();
                salary = input.nextDouble();

                if (ID == pID) {    
                    salary = salary + replenish;
                }
            }
            input.close();
        }

Im new to these things. Any help would be much appreciate.

我对这些东西很陌生。任何帮助将不胜感激。

采纳答案by Juned Ahsan

You have to use the approach of reading it from the original file line by line. Search and replace the salary with the new number. Write the content to a new temp file. Delete the original file. Finally replace the temp file to the original file name. Here is the code to do that:

您必须使用逐行从原始文件中读取它的方法。搜索并用新数字替换工资。将内容写入新的临时文件。删除原始文件。最后将临时文件替换为原始文件名。这是执行此操作的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileContentUpdater {

    public static void main(String args[]) throws IOException {
        String ID, Name;
        double salary;
        int replenish;

        Scanner console = new Scanner(System.in);
        System.out.print("Enter ID : ");
        String pID = console.nextLine();
        System.out.print("Enter replenish salary: ");
        replenish = console.nextInt();

        File originalFile = new File("file.txt");
        BufferedReader br = new BufferedReader(new FileReader(originalFile));

        // Construct the new file that will later be renamed to the original
        // filename.
        File tempFile = new File("tempfile.txt");
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

        String line = null;
        // Read from the original file and write to the new
        // unless content matches data to be removed.
        while ((line = br.readLine()) != null) {

            if (line.contains(pID)) {
                String strCurrentSalary = line.substring(line.lastIndexOf(" "), line.length());
                if (strCurrentSalary != null || !strCurrentSalary.trim().isEmpty()) {
                    int replenishedSalary = Integer.parseInt(strCurrentSalary.trim()) + replenish;
                    System.out.println("replenishedSalary : " + replenishedSalary);
                    line = line.substring(0,line.lastIndexOf(" ")) + replenishedSalary;
                }

            }
            pw.println(line);
            pw.flush();
        }
        pw.close();
        br.close();

        // Delete the original file
        if (!originalFile.delete()) {
            System.out.println("Could not delete file");
            return;
        }

        // Rename the new file to the filename the original file had.
        if (!tempFile.renameTo(originalFile))
            System.out.println("Could not rename file");

    }
}

回答by Nandeshwar

One possible way can be like this

一种可能的方式是这样的

  1. Read each line from file
  2. Split the line

  3. prepare another line with updated data and write to temp file

  4. Finally delete your old file and rename temp file to old file.

  5. Now you are done. Try the above algorithm.
  1. 从文件中读取每一行
  2. 分割线

  3. 用更新的数据准备另一行并写入临时文件

  4. 最后删除旧文件并将临时文件重命名为旧文件。

  5. 现在你完成了。试试上面的算法。