使用Java将文件移动到.eml目录

时间:2015-06-23 17:36:09

标签: java file

我使用以下代码将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" 文件。为什么是这样?我错过了什么?

更新:

以下是我调试时的值:

counter=0;
while(records_still_exist){

if(counter%4==0){

// open div code
}

...employee stuff...

if(counter%4==0){

// close div code
}

counter ++;
}

1 个答案:

答案 0 :(得分:2)

Files.move(source, target, options)中的目标是移动的实际目标。使用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);
    }
}

*“empty”包括其中只包含元文件的目录;例如,在Mac OS X上,仅包含 .DS_Store 元数据文件的目录被视为空。
来自javadoc:“在某些实现中,目录包含创建目录时创建的特殊文件或链接的条目。在这种实现中,当只存在特殊条目时,目录被视为空。” < / p>