java - 使用 Files.move 创建新的“文件”文件类型,而不是将文件移动到目录
问题描述
我正在尝试制作一个程序,从那里的单个文件夹中提取多个 MP4 文件并将它们放在已经创建的文件夹中(代码已稍作更改,因此它不会再弄乱任何 MP4,而是虚拟文本文件)。
我已经设法列出了指定文件夹中的所有文件夹/文件,但是在将它们移动到目录时遇到了麻烦。
static File dir = new File("G:\\New Folder");
static Path source;
static Path target = Paths.get("G:\\gohere");
static void showFiles(File files[]) {
for (File file : files) { // Loops through each file in the specified directory in "dir" variable.
if (file.isDirectory()) { // If the file is a directory.
File[] subDir = file.listFiles(); // Store each file in a File list.
for (File subFiles : subDir) { // Loops through the files in the sub-directory.
if (subFiles.getName().endsWith(".mp4")) { // if the file is of type MP4
source = subFiles.toPath(); // Set source to be the abs path to the file.
System.out.println(source);
try {
Files.move(source, target);
System.out.println("File Moved");
} catch (IOException e) {
e.getMessage();
}
}
}
} else {
source = file.toPath(); // abs path to file
try {
Files.move(source, target);
System.out.println("File moved - " + file.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
showFiles(dir.listFiles());
}
问题是当我将文件从源文件夹移动到目标时,它会删除或转换目标。
解决方案
Files.move
不像命令行。你在编程。你必须把事情说清楚。您实际上是在要求Files.move
这样做,以便target
(这里, G:\GoHere
) 从此成为您要移动的文件的位置。如果您打算:不,目标是G:\GoHere\TheSameFileName
您必须对此进行编程。
另外,您的代码一团糟。停止使用java.io.File
和java.nio.Path
一起。选择一方(选择java.nio
一方,这是一个新的 API 有充分的理由),不要混搭。
例如:
Path fromDir = Paths.get("G:\\FromHere");
Path targetDir = Paths.get(G:\\ToHere");
try (DirectoryStream ds = Files.newDirectoryStream(fromDir)) {
for (Path child : ds) {
if (Files.isRegularFile(child)) {
Path targetFile = targetDir.resolve(child.getFileName());
Files.move(child, targetFile);
}
}
}
resolve
给你一个Path
你在这里需要的对象:目标目录中的实际文件。
推荐阅读
- azure - Azure 服务总线消息:正文 v 标头
- python - 在熊猫中连接时如何保留空列?
- flutter - 更新TestFairy插件版本后如何解决错误?
- sql-server - 如何在 SSAS 表格中从 Excel Online 导入数据?
- woocommerce - Woocommerce:find_matching_product_variation 返回零
- python - django ValueError 无法查询“abcd@gmail.com”:必须是“对象”实例
- java - XStream 未加载旧版 QName XML
- python - 此行如何在 python 中引发“ValueError: Invalid format specifier”?
- sql - SQL Server 是否具有相当于 MySQL 的 JOIN USING 的功能?
- entity-framework - 实体框架联接是否应包含父表中的表?