JAVA IO - java中文件拷贝剪切的5种方式
@Test
void testCopyFile1() throws IOException {
File fromFile = new File("D:\data\test\newFile.txt");
File toFile = new File("D:\data\test2\copyedFile.txt");
try(InputStream inStream = new FileInputStream(fromFile);
OutputStream outStream = new FileOutputStream(toFile);) {
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
outStream.flush();
}
}
}
@Test
void testCopyFile2() throws IOException {
Path fromFile = Paths.get("D:\data\test\newFile.txt");
Path toFile = Paths.get("D:\data\test2\copyedFile.txt");
Files.copy(fromFile, toFile);
}
Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING);
CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(fromFile, toFile, options);
@Test
void testRenameFile() throws IOException {
Path source = Paths.get("D:\data\test\newFile.txt");
Path target = Paths.get("D:\data\test\renameFile.txt");
Files.move(source, target,StandardCopyOption.REPLACE_EXISTING);
}
@Test
void testRenameFile2() throws IOException {
Path source = Paths.get("D:\data\test\newFile.txt");
Files.move(source, source.resolveSibling("renameFile.txt"));
}
@Test
void testRenameFile3() throws IOException {
File source = new File("D:\data\test\newFile.txt");
boolean succeeded = source.renameTo(new File("D:\data\test\renameFile.txt"));
System.out.println(succeeded);
}
@Test
void testMoveFile() throws IOException {
Path fromFile = Paths.get("D:\data\test\newFile.txt");
Path anotherDir = Paths.get("D:\data\test\anotherDir");
Files.createDirectories(anotherDir);
Files.move(fromFile, anotherDir.resolve(fromFile.getFileName()),
StandardCopyOption.REPLACE_EXISTING);
}