I would like to copy a folder
c:\\data
into C:\\Users\\Matthew\\AppData\\Local\\Temp as is.
So then the path would be
C:\\Users\\Matthew\\AppData\\Local\\Temp\\data
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 standard java.nio.file.Files.copy(Path source, Path target, CopyOption... options)
. See here
You can use :
String tempPath = System.getenv("TEMP");
This reads the windows environment variable.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.