一、使用Java IO包的File类移动文件

Java IO包的File类提供了renameTo()方法,该方法可以用来移动文件。该方法的参数为一个File对象,代表目标文件的完整路径和文件名

示例代码:

File sourceFile = new File("sourceFilePath");
File destFile = new File("destinationFilePath");
if(sourceFile.renameTo(destFile)){
    System.out.println("File moved successfully");
}else{
    System.out.println("Failed to move file");
}

二、使用Java NIO包的Files类移动文件

Java NIO包的Files类提供了多个方法来移动文件。其中,Files.move()方法是最常用的方法。Files.move()方法接收三个参数:源文件路径、目标文件路径和移动选项。

示例代码:

Path sourcePath = Paths.get("sourceFilePath");
Path destPath = Paths.get("destinationFilePath");
Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);

StandardCopyOption.REPLACE_EXISTING 选项表示如果目标文件已经存在,则覆盖原文件。

三、使用Apache Commons IO库移动文件

Apache Commons IO库提供了FileUtils类,该类提供了移动文件的方法。FileUtils.moveFile()方法接收两个参数:源文件对象和目标文件对象。

示例代码:

File sourceFile = new File("sourceFilePath");
File destFile = new File("destinationFilePath");
try {
    FileUtils.moveFile(sourceFile, destFile);
} catch (IOException e) {
    e.printStackTrace();
}

FileUtils.moveFile()方法还提供了其他文件操作功能,例:复制文件、删除文件等。

四、使用Java IO流移动文件

除以上提到的方法外,我们还可以使用Java IO流来实现文件的移动。

示例代码:

File sourceFile = new File("sourceFilePath");
File destFile = new File("destinationFilePath");
InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
sourceFile.delete();