I want to append the content of one file to another existing file with content. I used plain file copy with FileOutputStream with append parameter and also with SequenceInputStream. Both are working for txt files but not for binary files like pdf and excel.
If i try to merge two pdf files always the second input stream is overwritten in the resultant file. Is there any other way i can achieve the same for binary files ?
Below is my code.
package org.saurav.simpletests.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
public class ConcatStreams {
public static void main (String a[]) {
ConcatStreams concatStreams = new ConcatStreams();
try {
InputStream input1 = new FileInputStream("<path to first binary file>");
InputStream input2 = new FileInputStream("<path to second binary file>");
OutputStream output = new FileOutputStream("<path to first binary file> ",true);
//concatStreams.mergeUsingSequenctInputStream(input1,input2); // uncomment it to run the code with sequenceInputStream
concatStreams.mergeUsingFileOutputAppend(output, input2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void mergeUsingFileOutputAppend(OutputStream outStream, InputStream input) {
try {
byte[] buffer = new byte[256];
int data;
data = input.read(buffer);
while(data != -1){
String str = new String(buffer, "UTF-8");
//System.out.println(str);
outStream.write(buffer);
data = input.read(buffer);
}
//output.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void mergeUsingSequenctInputStream(InputStream input1, InputStream input2) {
SequenceInputStream sequenceInputStream =
new SequenceInputStream(input1, input2);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("<path to first binary file>");
byte[] buffer = new byte[256];
int data;
data = sequenceInputStream.read(buffer);
while(data != -1){
String str = new String(buffer, "UTF-8");
//System.out.println(str);
fos.write(buffer);
data = sequenceInputStream.read(buffer);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Best Regards, Saurav