获取复制的文件

时间:2014-06-12 22:27:26

标签: java

我想将文件从一个文件夹复制到子文件夹然后重命名文件名,我创建了子文件夹并重命名了文件名,这部分:

for (int i = 0; i < list.length; i++) {
    String oldDir = path2;
    String oldName = list[i].toString();

    String newDir =oldDir+"\\sub";
    File pDir = new File(newDir);
    pDir.mkdir();
    String fileName = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss")
    .format(new Date());
    String newName = fileName+"_"+list[i].getName();

    File f = new File (oldDir, list[i].getName());
    if(f.renameTo(new File(newDir + newName))){
        System.out.println("File is moved successful!");
    }else{
        System.out.println("File is failed to move!");
    }}
}

但我无法将此重命名的文件复制到新的子文件夹中,它在父目录中重命名而不是旧文件名,我在哪里错了?

3 个答案:

答案 0 :(得分:1)

你的错误在&#39; if&#39;行:

if(f.renameTo(new File(newDir + newName))){

问题是你引用了旧文件f的文件对象,然后将其重命名为新目录,这不起作用(如NKukhar所说),因为它可能无法复制按照您的意愿提交文件。

答案 1 :(得分:0)

使用此代码:

public static void copyFile(File sourceFile, File destFile) {
    try {
        if (!sourceFile.exists()) {
            return;
        }
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        if (destination != null && source != null) {
            destination.transferFrom(source, 0, source.size());
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    } catch (IOException e) {

    }
}

第一个参数(sourceFile)是您要复制的文件,而destFile是您要将其复制到的文件(位于您的子文件夹中),以及您的新文件文件名

答案 2 :(得分:0)

在无法移动文件的情况下,File.renameTo()文档中存在某些情况:

     * Many aspects of the behavior of this method are inherently
     * platform-dependent: The rename operation might not be able to move a
     * file from one filesystem to another, it might not be atomic, and it
     * might not succeed if a file with the destination abstract pathname
     * already exists.  The return value should always be checked to make sure
     * that the rename operation was successful.