2

How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.

Have went through & tried the following:

My code:

    filePath = new File("").getAbsolutePath();
    BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
    try
    {                           
        String line = null;         
        while ((line = reader.readLine()) != null)
        {
            if (!(line.startsWith("*")))
            {
                //System.out.println(line);

                //check if target customer exists, via 2 fields - customer name, contact number
                if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
                {
                    System.out.println ("\nWelcome (Existing User) " + line + "!");

                    //w target customer, alter total number of bookings @ 5th line of 'Customer.txt', by reading lines sequentially
                    reader.readLine();
                    reader.readLine();
                    int total_no_of_bookings = Integer.valueOf(reader.readLine());

                    System.out.println (total_no_of_bookings);
                    reader.close();
                    valid = true;


                    //append total number of bookings (5th line) of target customer @ 'Customer.txt'
                    try {
                        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
                        writer.write(total_no_of_bookings + 1);
                        //writer.write("\n");
                        writer.close();
                    }
                    catch (IOException ex) 
                    {
                        ex.printStackTrace();
                    } 
                    //finally 
                   // {
                        //writer.close();
                    //}
                }                   
            }
        }       
Community
  • 1
  • 1
user2945412
  • 297
  • 1
  • 3
  • 13

4 Answers4

2

To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.

If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.

This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.

A4L
  • 17,353
  • 6
  • 49
  • 70
  • +1 "when done delete the old one an rename the temp file to be the same name as the old one" :) – async Nov 09 '13 at 20:14
1

The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.

To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.

Example of writing:

BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
Matthew Tory
  • 1,306
  • 2
  • 16
  • 30
  • the readline() is deliberate for me to get to a desired line. As for the implementation, how do I rewrite the text file & write the rest? any example please? or is this applicable? - http://www.raghuwansh.com/2013/07/10/write-text-file-in-java/ – user2945412 Nov 09 '13 at 19:51
  • You can use a BufferedWriter – Matthew Tory Nov 09 '13 at 19:57
  • trying now, question is, based on my question, I wish to overwrite the 5th line with some target value? Also, now i have the following error - Exception in thread "main" java.lang.Error: Unresolved compilation problem: writer cannot be resolved – user2945412 Nov 09 '13 at 20:06
  • omg, even if i take away the optional finally block, now my entire text gets erased :( please see my edit. – user2945412 Nov 09 '13 at 20:13
  • You mean nothing is written in your file? Perhaps close the reader before you open the writer? – Matthew Tory Nov 09 '13 at 20:25
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/40883/discussion-between-grimrader22-and-user2945412) – Matthew Tory Nov 09 '13 at 20:27
  • thank you, but the entire file is still overwritten. Please see my edit again. What am I missing or doing wrong? – user2945412 Nov 09 '13 at 20:28
  • +5000 for all the precise guidance! – user2945412 Nov 09 '13 at 22:14
1

You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.

Community
  • 1
  • 1
Josh
  • 1,563
  • 11
  • 16
0

AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.

So basically you have to create a function to do that read-insert-slice-rewrite

Andrea
  • 2,714
  • 3
  • 27
  • 38