首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将文件夹复制到临时目录中?

如何将文件夹复制到临时目录中?
EN

Stack Overflow用户
提问于 2014-10-24 05:56:16
回答 3查看 1.4K关注 0票数 1

我想复制一个文件夹

c:\data

按原样放入C:\Users\Matthew\AppData\Local\Temp。

所以路径应该是

C:\Users\Matthew\AppData\Local\Temp\data

这是我到目前为止所掌握的

代码语言:javascript
运行
复制
public void copyToTemp(File source){
    try {
        File dest = File.createTempFile(source.getName(), null);
        FileUtils.copyDirectory(source, dest);

        //change the source folder to the temp folder
        SOURCE_FOLDER = dest.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
EN

回答 3

Stack Overflow用户

发布于 2014-10-24 06:04:07

您可以使用标准java.nio.file.Files.copy(Path source, Path target, CopyOption... options)。请参阅here

票数 1
EN

Stack Overflow用户

发布于 2014-10-24 06:05:38

您可以使用:

代码语言:javascript
运行
复制
String tempPath = System.getenv("TEMP");

这将读取windows环境变量。

票数 0
EN

Stack Overflow用户

发布于 2014-10-24 06:24:45

代码语言:javascript
运行
复制
    public void copyToTemp(String source){
        File sourceFolder = new File(source);
        final String tempLocation = "C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Local\\Temp\\";
        File tempFolder = new File(tempLocation + sourceFolder.getName());

        tempFolder.mkdir();

        try{
            copy(sourceFolder, tempFolder);
        } catch(Exception e){
            System.out.println("Failed to copy file/folder to temp location.");
        }

    }

    private void copy(File sourceLocation, File targetLocation) throws IOException{
        if(sourceLocation.isDirectory()){
            copyDirectory(sourceLocation, targetLocation);
        } else{
            copyFile(sourceLocation, targetLocation);
        }
    }

    private void copyDirectory(File source, File target) throws IOException{
        if(!target.exists()){
            target.mkdir();
        }

        for(String f : source.list()){
            copy(new File(source, f), new File(target, f));
        }
    }

    private void copyFile(File source, File target) throws IOException{
        try(
                InputStream in = new FileInputStream(source);
                OutputStream out = new FileOutputStream(target)){
            byte[] buf = new byte[1024];
            int length;
            while((length = in.read(buf)) > 0){
                out.write(buf, 0, length);
            }
        }
    }

希望这能帮上忙卢克。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26538153

复制
相关文章

相似问题

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