0

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.

Esko
  • 29,022
  • 11
  • 55
  • 82
Scott
  • 1
  • 1
  • 1
  • 1
    Homework is always better when someone else is doing them for you. Or am I totally wrong and this is a production issue in real life? – Eran Medan Jan 01 '10 at 23:38
  • I'd rephrase this. It's poorly posed. Can you please add some more detail? – duffymo Jan 01 '10 at 23:38

2 Answers2

4

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
  • 811,555
  • 193
  • 1,581
  • 1,452
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);
    }
}
Anton
  • 12,285
  • 20
  • 64
  • 84