views:

101

answers:

2

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.

+4  A: 

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.

Mark Byers
A: 

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);
    }
}
Anton