如何更新.txt文件中的包含java [英] how to update the contain in .txt file java

查看:152
本文介绍了如何更新.txt文件中的包含java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  A123 Anna 3000 
A234 Alex 4000
A986 Jame 5000

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



输入ID:A123



输入补充工资:2000



运行程序后的file.txt:

  A123 Anna 5000 
A234 Alex 4000
A986 Jame 5000

这就是我所做的远,但它没有工作:

pre $ 公共静态无效addDalary()抛出IOException {
字符串ID,Nanme;
双薪;


扫描仪控制台=新扫描仪(System.in);
System.out.print(输入ID:);
String pID = console.nextLine();
System.out.print(输入补充工资:);
replenish = console.nextInt();

扫描仪输入=新扫描仪(新文件(file.txt));
while(input.hasNext()){
ID = input.next();
Name = input.next();
salary = input.nextDouble();

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

任何帮助将非常感激。

解决方案

您必须使用从原始文件逐行读取它的方法。搜索并用新号码替换工资。将内容写入新的临时文件。删除原始文件。最后将临时文件替换为原始文件名。这里是要做的代码:
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;
双薪;
int补货;

扫描仪控制台=新扫描仪(System.in);
System.out.print(输入ID:);
String pID = console.nextLine();
System.out.print(输入补充工资:);
replenish = console.nextInt();

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

//构造新的文件,稍后将被重命名为原来的
//文件名。
文件tempFile =新文件(tempfile.txt);
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

String line = null;
//从原始文件读取并写入新的
//除非内容匹配要删除的数据。
while(line = br.readLine())!= null){

if(line.contains(pID)){
String strCurrentSalary = line.substring(line .lastIndexOf(),line.length()); (strCurrentSalary.trim())isEmpty()){
int
System.out.println(replenishedSalary:+ replenishedSalary);
line = line.substring(0,line.lastIndexOf())+ replenishedSalary;
}

}
pw.println(line);
pw.flush();
}
pw.close();
br.close();
$ b $ //删除原始文件
if(!originalFile.delete()){
System.out.println(Could not delete file);
return;
}

//将新文件重命名为原始文件的文件名。
if(!tempFile.renameTo(originalFile))
System.out.println(Could not rename file);

}
}


for example i have the file named file.txt which contain personal information (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:

Enter ID: A123

Enter replenish salary: 2000

file.txt after run the program:

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.

解决方案

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

    }
}

这篇关于如何更新.txt文件中的包含java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆