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.
Asked
Active
Viewed 149 times
0
-
1What does this have to do with [tag:r.java-file]? What have you tried so far? Appending a file is a very basic task in file I/O. Show some effort. – Matt Ball Aug 12 '11 at 13:10
-
sorry, I was missed to listen r. before java-file – Silambarasan Aug 12 '11 at 13:12
2 Answers
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
-
Yes, I did like that only read file A line by line and appended to file B. My question is there is any way to append by just give file object, or file name? – Silambarasan Aug 12 '11 at 13:52
-
Your question does not say that. Are you using Apache Commons library? – gotomanners Aug 12 '11 at 14:19
-
I tried, But this is overwrite the content of destFile. I want's the content of srcFile to be append in destfile. – Silambarasan Aug 13 '11 at 06:41
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
-
-
-
`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