Java中移动文件或目录的方法盘点
时间: 2024-01-23 20:02:13 浏览: 35
在Java中移动文件或目录有多种方法,以下是其中几种:
1. 使用File类的renameTo()方法
```
File sourceFile = new File("sourceFile.txt");
File destFile = new File("destinationFile.txt");
if(sourceFile.renameTo(destFile)) {
System.out.println("File moved successfully!");
} else {
System.out.println("Failed to move the file!");
}
```
该方法将源文件或目录移动到指定的目标文件或目录,返回值为boolean类型,表示移动是否成功。
2. 使用Java NIO中的Files类的move()方法
```
Path sourcePath = Paths.get("sourceFile.txt");
Path destPath = Paths.get("destinationFile.txt");
Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
```
该方法将源文件或目录移动到指定的目标文件或目录,可以指定一些选项,如替换已存在的目标文件等。
3. 使用Apache Commons IO中的FileUtils类的moveFile()或moveDirectory()方法
```
File sourceFile = new File("sourceFile.txt");
File destFile = new File("destinationFile.txt");
FileUtils.moveFile(sourceFile, destFile);
```
```
File sourceDir = new File("sourceDir");
File destDir = new File("destinationDir");
FileUtils.moveDirectory(sourceDir, destDir);
```
该方法可以移动文件或目录,同时可以处理一些异常情况,如目标文件已存在等。
需要注意的是,移动文件或目录可能会涉及到文件权限、文件是否被占用等问题,所以在实际使用中需要谨慎处理。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)