Mike John
Mike John

Reputation: 818

Reading a file line by line then modifying a line and saving only that line

I have a file like this below, ints and a header that I don't want to change.

    a,b,c,d,e
    1,2,3,4,5
    44,2,20,5,4
    55,2,20,3,10
    ....

I want to search the numbers in the file. If the number is less than 5 I want to make the number 5. If it is greater than 50 I make the number 50.

        buffer = new BufferedReader(new FileReader(fileName));

        String headerOfFile = buffer.readLine();

        while((line = buffer.readLine()) != null)
        {
            String[] list = line.split(cvs);
            for(int i = 0; i < list.length; i++)
            {
                int t = Integer.parseInt(list[i]);
                if(t < 5)
                    t = 5;

                else if(t > 50)
                    t = 50;

                list[i] = t + "";

            // How do I save back into the file only this line after modifying it?
            }

        }

I might get a huge file so I don't want to read the whole thing into memory and then save.

Is there a way to save the line that I just modified back into the file at the correct position? Some sort of seek to line.

Upvotes: 0

Views: 65

Answers (1)

Tim B
Tim B

Reputation: 41188

You can use the Random Access File functionality in Java to do this sort of thing. The complication though is that you are potentially changing the length of things. If -3 changes to 5 then the number of digits change, if 123 changes to 50 the number of digits also change.

If you can make it work without changing the digit count (i.e. 05, 050) then you can just scan through the file modifying characters as you find them.

If not you might as well create a new file, stream in from one and out to the other processing as you go since any other approach is going to involve a nightmare of shuffling things around.

Just point an InputStream at the input file, OutputStream at a new output file and then scan through the Input (probably one line at a time) outputting the values (modified as required) to the output. Memory usage will be small and performance linear with file size

You can always delete the original and rename the new one once processing completes, although it's usually safer to keep the original.

Upvotes: 1

Related Questions