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.

2
  • 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? Commented Jan 1, 2010 at 23:38
  • I'd rephrase this. It's poorly posed. Can you please add some more detail? Commented Jan 1, 2010 at 23:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.