This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Prepending data to a file  RSS feed

 
Sujith Kannan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to know if there is any way in Java where I can prepend data to a file.
Currently yhis is what I have been doing-
ex) Let the file to be written to be Log_file
1.I rename the file to Log_file_temp.
2.Write the data I have in a buffer to the file Log_file.
3.Once this is over, I append the contents of the Log_file_temp to Log_file.
4.I delete the Log_file_temp.

This works fine,
but when the code is multithreaded,there are some unwanted conditions occurring.
So could you suggest a better way of doing the same.
Thanking you in advance,
Sujith
 
Karthik Guru
Ranch Hand
Posts: 1209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sujith,
am not sure if this is ok with you.
U can use ,
java.io.RandomAccessFile
RandomAccessFile f = new RandomAccessFile("file.txt","rw");
long length = f.length();
byte[] barr = new byte[(int)length];
f.read(barr);
String towrite = "what ever";
byte[] bwrite = towrite.getBytes();
f.seek(0);
f.write(bwrite);
f.write(barr);
f.close();
karthik.

 
Sujith Kannan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karthik,
Yes that works out.But if it is a very huge file the method is obviously not going to be efficient.Dont you think so?
Anyway thanks for the suggestion.I have used the same.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!