1

In Java I want to write a String to end of a specific line in file. The simple way:

BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
bw.write(String);

does not work because it always writes at the end of file. Is there a simple way?

s_puria
  • 397
  • 1
  • 8
  • 19
  • 2
    No, you will have to create a new file. Read all lines from the original file and copy them unaltered to the new file. When you reach the line that needs modification simply write that line + the new stuff to the file. – Marged Jun 29 '15 at 08:16
  • possible duplicate of [Inserting text into an existing file via Java](http://stackoverflow.com/questions/289965/inserting-text-into-an-existing-file-via-java) – Robin Krahl Jun 29 '15 at 08:18

1 Answers1

1

You have to get the line number where you want to add the string.... Then iterate over the the file with readLine().

while (br.readLine() != null) {
   if (actualLine == yourLine) // write the String
   actualLine ++;
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109