Domanda

I have a Java program that uses PrintWriter to write text to a file using lots of .println() statements, everything works fine. What I want to know is: is there a way to write to a specific line in the output file?

for example If my program writes 10 lines to the output file using 10 .println() statements. Is there a way that at the end of my program, I can tell it to write a line to the 3rd line of text in the file and that would then bump the remaining 7 lines down by one line to make room for the new 3rd line?

Any help would be greatly appreciated, Thanks in advance, Stephen.

È stato utile?

Soluzione

You can do this, but you have to do the bumping.

The simplest solution is to re-write the file with the extra line you need.

Or using RandomAccessFile, you can search for the third line, copy all the data in the file down, and insert the line you want to add.

Altri suggerimenti

No, PrintWriter can only overwrite a file or append to the end of it.

If you "overwrite" a line, the new line's length might differ from the original so all the content following the line would have to be shifted which PrintWriter cannot do.

Not only PrintWriter can't do that. All other Writers and OutputStreams can't do it either. Not even random access channels can do it (on its own).

This is because "a line" does not have a specific length. And in addition, if you want to insert something, you would have to move everything else that comes after it.

What you can do is to re-position a stream and overwrite that what is there.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top