how to write content in a Specific position in a File

前端 未结 5 1132
北海茫月
北海茫月 2020-11-29 10:07

Suppose I have a file named abhishek.txt and that contains the following line

I am , and what is your name.

Now I want to write

相关标签:
5条回答
  • 2020-11-29 10:45

    You have three choices:

    1. Pad the original entry with enough space that RandomAccessFile can be used (and you don't care about some extra trailing space. Easy, but limited utility
    2. Use a templating engine (StringTemplate, Velocity, etc) if you are doing this a lot. Possibly too much work if you are doing this just once.
    3. Write your own simple templating engine that reads it into memory does a regex replacement and writes it back. Not especially efficient but if you have very simple and limited usage, maybe the best compromise.
    0 讨论(0)
  • 2020-11-29 10:46

    You can't insert data into a file... file systems (in general) simply don't support such an operation. Typically you'd open one file for reading and another for writing, copy the first part of the file from one stream to the other, write the extra part, then copy the second part of the file.

    If you're trying to replace the original file, you'd then need to delete it and move the new file into place.

    Sometimes it may be simpler to read the whole file into memory in one go - it depends on exactly what you're trying to do, and how big the file is.

    0 讨论(0)
  • 2020-11-29 10:46

    Generally speaking you need to read the old file, modify the contents in memory and write it back out again.

    There are many options here, as to whether you read the file all at once, or a small piece at a time, whether you replace the existing file, etc, but this is generally the pattern to use.

    0 讨论(0)
  • 2020-11-29 10:55

    You can't insert data into a file. You can overwrite data at a specific location with RandomAccessFile. However an insert requires changing all of the data after it. For your case try something like this instead:

    File file = new File("abhishek.txt");
    Scanner scanner = new Scanner(file).useDelimiter("\n");
    String line = scanner.next();
    String newLine = line.substring(0, 5) + "Abhishek" + line.substring(5);
    FileWriter writer = new FileWriter(file);
    writer.write(newLine);
    writer.close();
    
    0 讨论(0)
  • 2020-11-29 10:56

    I managed to do it using RandomAccessFile:

    With this, you get a file containing exactly the expected 'I am Abhishek' content. This works even if you would had content after the first line, which you want to keep in the file(this was my initial problem: I had a large file and I had to insert some content after a certain String) rather than write at the end of the file, which is easier.

    0 讨论(0)
提交回复
热议问题