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

write and append with same streams.  RSS feed

 
Vishal Dharod
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am using this piece of code to create a new file and write something to it.
java.io.BufferedWriter out = new java.io.BufferedWriter(new java.io.FileWriter(filename,false));
out.write(_header);
out.write(_package);
out.close();

After this, if i want to open the same file and append the same things to the end of this file then what stream shuld i use. BufferedWriter does not have a seek function which will take me to the end of the file. I want to ues the same function to append to the file so that there is no redundancy.
-- Vishal.
 
Vishal Dharod
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well thats true, 'append = true' would allow appending at the end of file , but i want to append to the middle of the file and so i need a file pointer which would take me there.
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You probably want to look at RandomAccessFile
 
Vishal Dharod
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried using RandomAccesFile class but it appends binary characters to the file i am trying to append to.
This is what I use :
try {
RandomAccessFile out = new RandomAccessFile(filename, "rw");
System.out.println("length of fie = " + out.length());
out.seek(out.length() - 5);
out.writeChars("here i am " );

out.close();
} catch (IOException e) {
}
And after running this, the file is appended with some binary chars
-- Vishal.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!