项目中通过代码来实现文件的移动
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FileMoveExample {
public static void main(String[] args) {
String sourceFilePath = "path/to/source/file.txt";
String destinationFolderPath = "path/to/destination/folder";
try {
Path sourcePath = Path.of(sourceFilePath);
Path destinationPath = Path.of(destinationFolderPath, sourcePath.getFileName().toString());
Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File moved successfully.");
} catch (IOException e) {
System.out.println("Failed to move the file: " + e.getMessage());
}
}
}
上述代码中,首先指定了源文件的路径sourceFilePath和目标文件夹的路径destinationFolderPath。然后,使用Path.of()方法创建源文件和目标文件的Path对象。接下来,使用Files.move()方法将源文件移动到目标文件夹中,并使用StandardCopyOption.REPLACE_EXISTING选项来替换已存在的文件。最后,通过捕获IOException来处理可能的移动失败情况。