linux命令
linux中是有mv 源路径 目标路径
以及cp 源路径 目标路径
的方法实现文件的移动并改名以及文件的复制并改名。在java中可以使用其他方法代替。
java操作
文件复制到指定路径并删除源文件 = 文件移动
使用 Files 类(Java 7及以上版本)
public class FileCopyExample {
public static void main(String[] args) {
Path source = Paths.get("sourceFile.txt");
Path target = Paths.get("targetFile.txt");
try {
Files.copy(source, target);
System.out.println("File copied successfully.");
} catch (IOException e) {
System.err.println("Failed to copy file: " + e.getMessage());
}
}
}
使用 InputStream 和 OutputStream
public class FileCopyExample {
public static void main(String[] args) {
String sourceFile = "sourceFile.txt";
String targetFile = "targetFile.txt";
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.err.println("Failed to copy file: " + e.getMessage());
}
}
}
FileChannel
public class FileCopyExample {
public static void main(String[] args) {
String sourceFile = "sourceFile.txt";
String targetFile = "targetFile.txt";
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
FileChannel sourceChannel = fis.getChannel();
FileChannel targetChannel = fos.getChannel()) {
targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
System.out.println("File copied successfully using FileChannel.");
} catch (IOException e) {
System.err.println("Failed to copy file: " + e.getMessage());
}
}
}
使用 transferFrom() 方法来实现文件复制操作。这种方法利用了底层操作系统的零拷贝特性,效率更高。