Arne Vajh??j wrote:
On 08-10-2010 08:03, Sahil Dave wrote:
What is the established way of copying a file/dir into another dir in
Java?
I was looking into 'java.io' package, but could only find a renameTo()
method. It looks like it only renames the file or at the moves the
same file to the destination dir.
Just write code that does it.
public static void copy(String fromname, String toname) throws
IOException {
InputStream is = new FileInputStream(fromname);
OutputStream os = new FileOutputStream(toname);
byte[] b = new byte[100000];
int n;
while((n = is.read(b))>= 0) {
os.write(b, 0, n);
}
is.close();
os.close();
}
or similar.
If you want to copy streams, it's better to use IOUtils provided by Apache
Commons instead of hardcoded while and read:
IOUtils.copy(InputStream input, OutputStream output)
http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,
%20java.io.OutputStream%29