Let's say I have a txt file:Hello World I want to just add "My" in between so that the file looks like this:Hello My World I was trying to achieve this using java.nio.channels.FileChannel class as you can seek the file pointer.But when I move the file pointer to the middle of the file and I write the text it replaces the text in front instead of just pushing it forward.
My Code:
try{
FileChannel out=FileChannel.open(Paths.get("E:\\trial.txt"),StandardOpenOption.WRITE);
out.position(6);
out.write(ByteBuffer.wrap("My ".getBytes()));
}catch(IOException e){
e.printStackTrace();
}
Output:Hello My ld
Desired Output:Hello My World
As you can see "My " replaces "Wor" i don't want any text to be replaced,it should just add "My " in between the file. I am aware that I could do it by reading "World"(remaining text after specified position) and creating a ByteBuffer of "My World" and then writing it at the desired position.
This does the job:
try{
FileChannel out=FileChannel.open(Paths.get("E:\\trial.txt"),StandardOpenOption.READ,StandardOpenOption.WRITE);
out.position(6);
ByteBuffer b=ByteBuffer.allocate(20);
b.put("My ".getBytes());
out.read(b);
out.position(6);
b.flip();
out.write(b);
}catch(IOException e){
e.printStackTrace();
}
But Is there an easier/direct appproach of doing this in which you just set the file pointer to a specific position and write just adds the text without replacing the existing text?
You could go through all lines in the file and save them in an Array. Then you just for loop through and at the end print your stuff in it.