我想复制一个文件夹
C:\数据
按原样进入C:\ Users \ Matthew \ AppData \ Local \ Temp。
那么路径就是
C:\用户\马修\应用程序数据\本地\ 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();
}
}
答案 0 :(得分:1)
您可以使用标准java.nio.file.Files.copy(Path source, Path target, CopyOption... options)
。
见here
答案 1 :(得分:0)
您可以使用:
String tempPath = System.getenv("TEMP");
这将读取windows环境变量。
答案 2 :(得分:0)
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);
}
}
}
希望这会有所帮助,卢克。