Search code examples
javaseekrandomaccessfile

search a string in file and insert content above


I try to search a string inside a txt-file and insert some specific content above it. Sadly the output looks quite different from what I expect.

Can somebody give me a hint?
This is how far I got!

    String description= "filename.txt";
    String comparison="    return model;";
    RandomAccessFile output = null;
        try
        {
          output = new RandomAccessFile(description, "rw" );
          String line = null;
          while ((line = output.readLine()) != null) {
                  if (line.equals(comparison)){
                      //System.out.println("alt: "+line);
                      output.seek(output.getFilePointer()-line.getBytes().length);
                      output.writeChars("new stuff; \n");
                      //System.out.println("new: "+output.readLine());
                      }
          }
        }
        catch ( IOException e ) {
          e.printStackTrace();
        }
        finally {        
          if ( output != null ){ try { output.close(); } catch ( IOException e ) { e.printStackTrace(); }}
        }

This is the file I try to read:

/*filename.txt*/
    some longer content ~ 100kB

    return model;

    further content 

and this is what I hope to get

/*filename.txt*/
    some longer content ~ 100kB

    new stuff;

    return model;

    further content 

Solution

  • Files don't support insertion or deletion of content except at the end of the file. (It's not a limitation of Java but the OS)

    To insert text, you must re-write the file (at the least from the point you want to alter) The simplest solution is to copy content to a temporary file, altering/inserting or deleting as required and replacing the original if this is sucessful.