簡體   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