繁体   English   中英

如何将文件夹复制到temp目录?

[英]How do I copy a folder into the temp directory?

我想复制一个文件夹

C:\\数据

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

因此,路径将是

C:\\ Users \\用户马修\\应用程序数据\\本地的\\ Temp \\数据

这是我到目前为止的

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();
    }
}

您可以使用标准的java.nio.file.Files.copy(Path source, Path target, CopyOption... options) 这里

您可以使用 :

String tempPath = System.getenv("TEMP");

这将读取Windows环境变量。

    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);
            }
        }
    }

希望这会有所帮助,卢克。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM