• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to write to specific line number in a Text file?  RSS feed

 
Ryan Webb
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers!

is there a way to write to a text file but writing only to a specific line number only?

For example:
I have a 10-line text file, I only want to change line number 4 and the rest will not change.
Now how, can I accomplish this without using loop? (reason for optimization - if possible)

thanks!
Ryan Webb
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JavaRanch FAQ: EditAnExistingFile
 
xsunil kumar
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First read the file and then there is a method in file handling(readline). Declare one veriable and increement this variable on each readline method. when value becomes 4, then append new content in earlier created buffer reader. and read remaining file , put in same buffer and finallly write it again.

It will insert your code at your specific line.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!