本文共 1713 字,大约阅读时间需要 5 分钟。
Java提供了在目录之间移动文件的功能。这里描述了实现此目的的两种方法。第一种方法利用Files包进行移动,而另一种方法首先将文件复制到目标,然后从源中删除原始副本。
使用Files.Path move()方法:
将文件永久重命名并移动到新位置。
句法:
public static Path move(Path source, Path target, CopyOption..options)
throws IOException
参数:
source - 要移动目标文件
target - 目标文件的路径
(可能与源路径的不同提供者相关联)
options - 指定应如何完成移动的选项
返回:目标文件的路径
// Java program to illustrate renaming and
// moving a file permanently to a new loaction
import java.io.*;
import java.nio.file.Files;
import java.nio.file.*;
public class Test
{
public static void main(String[] args) throws IOException
{
Path temp = Files.move
(Paths.get("C:\\Users\\Mayank\\Desktop\\44.txt"),
Paths.get("C:\\Users\\Mayank\\Desktop\\dest\\445.txt"));
if(temp != null)
{
System.out.println("File renamed and moved successfully");
}
else
{
System.out.println("Failed to move the file");
}
}
}
输出:
File renamed and moved successfully
使用Java.io.File.renameTo()和Java.io.File.delete()方法:
使用这两种方法复制文件并删除原始文件。
renameTo()的语法:
public boolean renameTo(File dest)
说明:重命名此抽象路径名称表示的文件。
参数: dest - 指定文件的新抽象路径名
返回:当且仅当重命名成功时才返回 true; 否则是假的
delete()的语法:
public boolean delete()
描述:删除文件或目录
由此抽象路径名称表示。
返回:当且仅当文件或时,返回 true
目录已成功删除; 否则是false的
// Java program to illustrate Copying the file
// and deleting the original file
import java.io.*;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Users\\Mayank\\Desktop\\1.txt");
// renaming the file and moving it to a new location
if(file.renameTo
(new File("C:\\Users\\Mayank\\Desktop\\dest\\newFile.txt")))
{
// if file copied successfully then delete the original file
file.delete();
System.out.println("File moved successfully");
}
else
{
System.out.println("Failed to move the file");
}
}
}
输出
File moved successfully
转载地址:http://azsxl.baihongyu.com/