Reputation:
I would like to write a function copy(File f1, File f2) f1 is always a file. f2 is either a file or a directory.
If f2 is a directory I would like to copy f1 to this directory (the file name should stay the same).
If f2 is a file I would like to copy the contents of f1 to the end of the file f2.
So for example if F2 has the contents:
2222222222222
And F1 has the contents
1111111111111
And I do copy(f1,f2) then f2 should become
2222222222222
1111111111111
Thanks!
Upvotes: 6
Views: 20193
Reputation: 14658
Using the code from the answer by Allain Lolande and extending it, this should address both parts of your question:
File f1 = new File(srFile);
File f2 = new File(dtFile);
// Determine if a new file should be created in the target directory,
// or if this is an existing file that should be appended to.
boolean append;
if (f2.isDirectory()) {
f2 = new File(f2, f1.getName());
// Do not append to the file. Create it in the directory,
// or overwrite if it exists in that directory.
// Change this logic to suite your requirements.
append = false;
} else {
// The target is (likely) a file. Attempt to append to it.
append = true;
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(f1);
out = new FileOutputStream(f2, append);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
Upvotes: 5
Reputation: 13604
Apache Commons IO to the rescue!
Expanding on Allain's post:
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true); // appending output stream
try {
IOUtils.copy(in, out);
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
Using Commons IO can simplify a lot of the stream grunt work.
Upvotes: 17
Reputation: 93348
FileOutputStream has a constructor that allows you to specify append as opposed to overwrite.
You can use this to copy the contents of f1 to the end of f2 as below:
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Upvotes: 2
Reputation: 2308
Check out the link below. it is a source file that copies a file to another using NIO.
http://www.java2s.com/Code/Java/File-Input-Output/CopyafileusingNIO.htm
Upvotes: 1