Retrieving and Replacing number in text file

社会主义新天地 提交于 2019-12-08 13:02:54

问题


I need to retrieve and change a number in a text file that will be in the first line. It will change lengths such as "4", "120", "78" to represent the data entries held in the text file.


回答1:


If you need to change the length of the first line then you are going to have to read the entire file and write it again. I'd recommend writing to a new file first and then renaming the file once you are sure it is written correctly to avoid data loss if the program crashes halfway through the operation.




回答2:


This will read from MyTextFile.txt and grab the first number change it and then write that new number and the rest of the file into a temporary file. Then it will delete the original file and rename the temporary file to the original file's name (aka MyTextFile.txt in this example). I wasn't sure exactly what that number should change to so I arbitrarily made it 42. If you explain what data entries the file contains I could help you more. Hopefully this will help you some anyways.

import java.util.Scanner;
import java.io.*;

public class ModifyFile {
    public static void main(String args[]) throws Exception {
        File input = new File("MyTextFile.txt");
        File temp = new File("temp.txt");
        Scanner sc = new Scanner(input);    //Reads from input
        PrintWriter pw = new PrintWriter(temp); //Writes to temp file

        //Grab and change the int
        int i = sc.nextInt();
        i = 42;

        //Print the int and the rest of the orginal file into the temp
        pw.print(i);
        while(sc.hasNextLine())
            pw.println(sc.nextLine());

        sc.close();
        pw.close();

        //Delete orginal file and rename the temp to the orginal file name
        input.delete();
        temp.renameTo(input);
    }
}


来源:https://stackoverflow.com/questions/1990036/retrieving-and-replacing-number-in-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!