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
Abhishek
after "I am" like I am Abhishek, .. How to write the content in this specific position directly.
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();
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.
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.
You have three choices:
- 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
- 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.
- 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.
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.
来源:https://stackoverflow.com/questions/5786697/how-to-write-content-in-a-specific-position-in-a-file