Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Writing to a File

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,
I would like to open a file in append mode and wwant to write to it. Can someone help me in explaning how to go about on this. I know randomaccessfile can be opened in "rw" mode. But i am not sure how to do for writing in append mode.
Thanks for all your help!!!
Regards,
Parasu.
 
Ranch Hand
Posts: 347
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you know how to open the random access file in rw mode, all you need to do to append data to the end of the file is:
1.) move the file pointer to the end of the file and
2.) start writing.
An example is given below. (The example assumes you already have a file called "test.dat" on your system).
import java.io.*;
public class Test
{
public static void main(String args[])
{
String fileName = "test.dat"; // the name of the file to // which we write
RandomAccessFile raf; // the random access file
String dataToAppend = "Adding another string."; // the // data to append
try
{
// create the random access file
raf = new RandomAccessFile(fileName, "rw");
// determine the file's current length
long end = raf.length();
// seek to the end of the file
raf.seek(end);
// write the data to the file
raf.writeChars(dataToAppend);
// close the file
raf.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Hope this helps.
Stephanie
 
But how did the elephant get like that? What did you do? I think all we can do now is read this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic