gpt4 book ai didi

java - 使用 Java 移动文件将目录更改为 .eml

转载 作者:行者123 更新时间:2023-12-02 04:34:35 24 4
gpt4 key购买 nike

我使用以下代码将 .eml 文件从一个目录移动到另一个目录:

if(Files.exists(Paths.get(newDirectoryPath))){
try {
Files.move(Paths.get(filePath), Paths.get(newDirectoryPath), REPLACE_EXISTING);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
new File(newDirectoryPath).mkdir();
moveFile(filePath, newDirectoryPath);
}

目录创建正常,但是当我将文件移动到新目录时,该目录变成 .eml 文件。为什么是这样?我错过了什么?

更新:

这是我调试时的值:

filePath = "/Users/absolute/path/to/my/file/myfile.eml";
newDirectoryPath = "/Users/absolute/path/to/my/new/directory/CompleteKsc"

最佳答案

Files.move(source, target, options) 中的target 是移动的实际目标。使用REPLACE_EXISTING,您的调用将删除现有目标(您的目录),然后将源移动到该名称。
仅当目录为空时才会将其删除*,否则调用将抛出 DirectoryNotEmptyException。

如果要将文件移动到目录中同名的文件,则必须将文件名附加到目标。

javadoc for move有一个使用 newdir.resolve(...) 来完成您想要的操作的示例。

转换您的原始代码以遵循该示例会给出以下结果:

public void moveFile(String source, String targetDir)
{
Path dirpath = Paths.get(targetDir);

if (Files.exists(dirpath)) {

Path target = dirpath.resolve(targetDir);

try {
Files.move(Paths.get(source), dirpath.resolve(target), REPLACE_EXISTING);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
new File(targetDir).mkdir();
moveFile(source, targetDir);
}
}
<小时/>

* “空”包括仅包含元文件的目录;例如,在 Mac OS X 上,仅包含 .DS_Store 元数据文件的目录被视为空。
来自 javadoc:“在某些实现中,目录具有在创建目录时创建的特殊文件或链接的条目。在此类实现中,当仅存在特殊条目时,目录被视为空。”

关于java - 使用 Java 移动文件将目录更改为 .eml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31009664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com