[英]How do I copy a folder into the temp directory?
I would like to copy a folder 我想复制一个文件夹
c:\\data C:\\数据
into C:\\Users\\Matthew\\AppData\\Local\\Temp as is. 照原样放入C:\\ Users \\ Matthew \\ AppData \\ Local \\ Temp。
So then the path would be 因此,路径将是
C:\\Users\\Matthew\\AppData\\Local\\Temp\\data C:\\ Users \\用户马修\\应用程序数据\\本地的\\ Temp \\数据
Here is what I have so far 这是我到目前为止的
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();
}
}
You can use : 您可以使用 :
String tempPath = System.getenv("TEMP");
This reads the windows environment variable. 这将读取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);
}
}
}
Hope this helps, Luke. 希望这会有所帮助,卢克。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.