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

小编典典

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

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

}

}

2020-11-19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值