This week's giveaway is in the Threads forum.
We're giving away four copies of Java Concurrency Live Lessons and have Doug Schmidt on-line!
See this thread for details.
Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

BufferWriter... help please  RSS feed

 
ramesh sk
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi javaranchers,
please give me an idea to do this ,
i'm using BufferedWriter to write some records in a file and when i want to write or insert some more records in that file that new records should add before the previous records. means when i'm inserting some data it should add at the first place.
i'm not giving any code here pl excuse it,and my idea is take all records in StringBuffer and take another StringBuffer put all the new records in this and append the previous StringBuffer to this. i'm thinking that it wiil be more burden on the jvm.
pl give any idea to do this .
thanks in advance,
ramesh
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15865
81
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't insert data somewhere in the middle of a file if you use BufferedWriter. In fact, I don't think there's anything in the standard Java API that allows you to insert data in the middle of a file.

If you want to insert data in the middle of the file, the only solution is:

(1) open the original file for reading,
(2) open a new temporary file for writing,
(3) copy the content of the original file up to the point where you want to insert data to the temp file,
(4) write the data to be inserted to the temp file,
(5) write the rest of the original file to the temp file,
(6) close both files,
(7) delete the original file,
(8) rename the temp file to the name of the original file.

If you want to do database-like things using files, you're probably better off by using a real database. You could use a small, embedded database like hsqldb.
[ October 07, 2005: Message edited by: Jesper de Jong ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!