栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何更新.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");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/509696.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号