Reputation: 2859
I want all the features of file.renameTo in java but without the source file getting deleted. For eg: Say I have a file report.doc and I want to create the file report.xml without report.doc getting deleted. Also, the contents of both the files should be the same. (A simple copy) How do I go about doing this?
I know this might be trivial but some basic searching didn't help.
Upvotes: 0
Views: 3558
Reputation: 29680
You can create a new File with the same content of the original.
Use the java NIO (Java 1.4 or later) for that:
private static void copy(File source, File destination) throws IOException {
long length = source.length();
FileChannel input = new FileInputStream(source).getChannel();
try {
FileChannel output = new FileOutputStream(destination).getChannel();
try {
for (long position = 0; position < length; ) {
position += input.transferTo(position, length-position, output);
}
} finally {
output.close();
}
} finally {
input.close();
}
}
see the answers for this question for more
Upvotes: 1
Reputation: 188014
For filesystem operations Apache Commons IO provides useful shortcuts.
See:
Upvotes: 3