Question

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 
Was it helpful?

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.

OTHER TIPS

Use two files. Copy until which line you want into a new file. Add your new line. Then again copy the rest of the lines into the file. Finally, copy the whole content of the new file into the old file

First of all: there is white space in the string you're testing for:

String comparison="    return model;";

It would be a better idea to compare the lines like this:

if (line.trim().equals(comparison.trim())){ ...

The call to trim() will remove all whitespaces/tabs in the line and the comparison string, so it would match also if some file uses tabs instead of whitespaces, or a different number of whitespaces...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top