File Copy

How do I copy a file without having to create an empty file from scratch and having to read the content of old file and write to new file?
[145 byte] By [lowtechbillya] at [2007-10-2 10:56:51]
# 1

You could use the io-package from Apache Commons:

http://jakarta.apache.org/commons/io/apidocs/org/apache/commons/io/IOUtils.html

Example:

import org.apache.commons.io.IOUtils;

import java.io.*;

class CommonsFileCopy {

public static void main(String[] args) {

String fIn = "CommonsFileCopy.java";

String fOut = "(copy) CommonsFileCopy.java";

try {

InputStream inStream = new BufferedInputStream(new FileInputStream(fIn));

OutputStream outStream = new FileOutputStream(new File(fOut));

IOUtils.copy(inStream, outStream);

System.out.println("Copied \""+fIn+"\" to \""+fOut+"\" successfully.");

}

catch(IOException ioe) { ioe.printStackTrace(); }

}

}

prometheuzza at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 2
I want the OS to handle the file copy, I dont want my code to copy the content from one file to a newly created file.
lowtechbillya at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 3
> I want the OS to handle the file copy, I dont want my> code to copy the content from one file to a newly> created file.Why?
RageMatrix36a at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 4
Regardless, can't you invoke the runtime.exec and do your copy using "copy" or whatever the command is under your OS?
RageMatrix36a at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 5

You probably have Windows:

String file = "test.txt";

String copy = "copy_test.txt";

String command = "copy "+file+" "+copy;

Runtime.getRuntime().exec("cmd /c "+command);

prometheuzza at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 6
> I want the OS to handle the file copy, I dont want my> code to copy the content from one file to a newly> created file.I now understand your handle!
sabre150a at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 7
> I now understand your handle!; )
prometheuzza at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...
# 8
OK, so I have to invoke runtime then. Thanks.
lowtechbillya at 2007-7-13 3:22:34 > top of Java-index,Java Essentials,New To Java...