Datei kopieren
Hier wird einfach eine Datei kannweg.txt nach kannweg.bak kopiert (ab Java 7):
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileCopy { public static void main(String[] args) throws IOException { Path source = Paths.get("C:/temp/kannweg.txt"); Path destination = Paths.get("C:/temp/kannweg.bak"); Files.copy(source, destination); } }
FotoStacker, Fotos günstig kaufen
Natürlich kann man auch mit Javaversion 6 oder früher Dateien kopieren. Die folgende Funktion ist ein Beispiel dafür:
private boolean copyFile(final File src, final File dest) throws IOException {
FileChannel srcChannel = new FileInputStream(src).getChannel();
FileChannel destChannel = new FileOutputStream(dest).getChannel();
try {
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (srcChannel != null)
srcChannel.close();
if (destChannel != null)
destChannel.close();
}
return true;
}