Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write content in a Specific position in a File

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.

like image 383
Abhishek Choudhary Avatar asked Apr 26 '11 06:04

Abhishek Choudhary


4 Answers

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.

like image 167
Jon Skeet Avatar answered Sep 26 '22 08:09

Jon Skeet


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();
like image 28
WhiteFang34 Avatar answered Sep 24 '22 08:09

WhiteFang34


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.

like image 35
MeBigFatGuy Avatar answered Sep 26 '22 08:09

MeBigFatGuy


I managed to do it using RandomAccessFile:

enter image description here

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.

like image 26
Crenguta S Avatar answered Sep 22 '22 08:09

Crenguta S