首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取复制的文件

问获取复制的文件
EN

Stack Overflow用户
提问于 2014-06-13 06:27:26
回答 3查看 60关注 0票数 2

我想将文件从一个文件夹复制到子文件夹,然后重命名文件名,我创建了子文件夹并重命名了文件名,其中包含以下部分:

代码语言:javascript
复制
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!");
    }}
}

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

EN

回答 3

Stack Overflow用户

发布于 2014-06-13 06:51:22

你的错误出现在'if‘行上:

代码语言:javascript
复制
if(f.renameTo(new File(newDir + newName))){

问题是,您引用的文件对象是旧文件f,然后将其重命名为新目录,这是不起作用的(正如NKukhar所指出的),因为它可能不会像您希望的那样复制文件。

票数 1
EN

Stack Overflow用户

发布于 2014-06-13 06:35:08

使用以下代码:

代码语言:javascript
复制
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是您要将其复制到的文件(位于您的子文件夹中),并且使用新的文件名

票数 0
EN

Stack Overflow用户

发布于 2014-06-13 06:37:22

在File.renameTo()的文档中有一些文件无法移动的情况:

代码语言:javascript
复制
     * 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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24194869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档