0

I want to Append the content of FIleA.csv to an other FileB.csv in java. is there any method to do this operation. Or to read from FIleA.csv and append to fileB.csv manually? I need your valuable suggestion.. Thanx in Advance.

Silambarasan
  • 299
  • 2
  • 4
  • 14

2 Answers2

2

When creating the outputStream for the file you want to append to, a second argument true will enable "append mode" on the file instead of "overwrite mode".

new FileOutputStream(f, true);

See the docs

EDIT

If you are can use the Apache Commons Library, it has a copyFile() method that will do just what you want.

You need at least the commons-io.2.0.1.jar(latest version) in your classpath to use this library.

Community
  • 1
  • 1
gotomanners
  • 7,808
  • 1
  • 24
  • 39
1

With Apache commons IO, it would take approximately 2 lines of code : (Indeed 4 as you have to manually close the output file)

import java.util.*;
import java.io.*;
import org.apache.commons.io .*;

public class ConcatCSV
{
  public static void main(String[] a )
  {
    try
    {
        Collection<String > listLines = IOUtils.readLines( new FileReader( new File( "a.csv" ) ) );
        FileWriter fw = new FileWriter( new File( "b.csv" ),true ) ;
        IOUtils.writeLines( listLines, System.getProperty( "line.separator" ), fw );
        fw.close();
    }//try
    catch( Exception ex )
    {
        ex.printStackTrace();
    }//catch
   }//main
}//class

Regards, Stéphane

Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • Your code reads the two files and writes them to a third one. The OP wants to append file A to file B. No need to read B to do this. – JB Nizet Aug 12 '11 at 13:23
  • What's mean IOutils in your code? – Silambarasan Aug 12 '11 at 13:46
  • addAll will concat a csv file... – Snicolas Aug 12 '11 at 14:48
  • `Collection listLines = IOUtils.readLines( new FileReader( new File( srcFileName ) ) ); listLines.addAll( IOUtils.readLines( new FileReader( new File( srcFileName ) ) ) ); IOUtils.writeLines( listLines, System.getProperty( "line.separator" ), new FileWriter( new File( destFileName ) ) );` I did like it, but the destFileName remain empty and didn't get any exception – Silambarasan Aug 13 '11 at 06:55
  • Ok, I edited the previous code. The problem came from not closing the final writer. I even found something shorter. – Snicolas Aug 13 '11 at 12:06