Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Mar 20, 1997

Appending to a File

Question:
How can I append to a file in Java? The file is ASCII. It exists. The program has rights to the file. I just need to add to the end of the file.

Answer:
You need to use Java's RandomAccessFile class to accomplish this. Once you open a file with read and write permissions, you can simply seek to the end position of the file and write your data from that point using one of the various write methods available in that class:

       public void write(byte  b[]);
       public void write(byte  b[], int  off, int  len);
       public void write(int  b);
       public final void writeBoolean(boolean  v);
       public final void writeByte(int  v);
       public final void writeBytes(String  s);
       public final void writeChar(int  v);
       public final void writeChars(String  s);
       public final void writeDouble(double  v);
       public final void writeFloat(float  v);
       public final void writeInt(int  v);
       public final void writeLong(long  v);
       public final void writeShort(int  v);
       public final void writeUTF(String  str);
For example, the following program appends a string from the command line to the end of a file:
------------------- FileAppend.java -----------------

import java.io.*;

public class FileAppend {
       //
       // Defining a main() routine allows the program to be
       // run as a standalone java application
       //
       public static void main(String argv[]) {
               if (argv.length != 2) {
                       System.out.println("Usage: FileAppend string outfile");
                       System.exit(1);
               }

               RandomAccessFile output = null;
               try {
                       // Open the file for reading and writing
                       output = new RandomAccessFile(argv[1], "rw");
               } catch (Exception e) {
                       System.out.println("Couldn't open " + argv[1]);
                       System.exit(1);
               }

               try {
                       // seek to the end of the file
                       output.seek(output.length());
                       // perform the write operation
                       output.writeChars(argv[0] + "\n" );
               } catch (Exception e) {
                       System.out.println("Error appending to file");
                       System.exit(1);
               }
       }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date