Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Editing a specific line in a text file  RSS feed

 
James Farber
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, say I have a text file called "people.txt", and it contains the following information:

1 adam 20 M
2 betty 49 F
3 charles 9 M
4 david 22 M
5 ethan 41 M
6 faith 23 F
7 greg 22 M
8 heidi 63 F

Basically, the first number is the ID of the person, then comes the person's name, age and gender. Say I want to replace line 2, or the person with ID number 2 with different values. Now, I know I cant use RandomAccessFile for this because the names are not always the same number of bytes, neither are the ages. While searching random Java forums, I found that StringBuilder or StringBuffer should suffice for my needs, but I'm not sure how to implement either. Can they be used to directly write to the text file? I want this to work directly from user input.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there is no way to edit files directly like you would want to. You'll have to do it like this:

1. Open the current file for reading.
2. Open a new file for writing.
3. Copy the data from the current to the new file upto the point where you want to modify data.
4. Write the modified data to the new file.
5. Copy the rest of the current file to the new file.
6. Close the files.
7. Delete the current file and rename the new file to the name of the current file.

StringBuilder and StringBuffer are not classes that you can use to write to files. Look them up in the API documentation.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!