Java- Copy file to new file or existing file

I would like to write a copy of the function (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 remain unchanged).

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:

222222222222222

And F1 has the contents

1111111111111

And I copy (f1, f2), then f2 should become

222222222222222

1111111111111

Thanks!

+4
source share
4 answers

Apache Commons IO to the rescue!

Extension on the Allain page:

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 work with the grunt stream.

+17
source

Using the code from Allain Lolande's answer and extending it, this should affect 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(); } } 
+5
source

FileOutputStream has a constructor that allows you to specify append rather than rewrite.

You can use this to copy the contents of f1 to the end of f2, as shown 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(); 
+2
source

Check out the link below. This is the source file that copies the file to another using NIO.

http://www.java2s.com/Code/Java/File-Input-Output/CopyafileusingNIO.htm

+1
source

All Articles