Move a file to a shared drive in Java

Categories Information Technology, Programming

I had a bit of trouble with this, in a program I’m writing at the moment. Every time I tried to move a file to a shared folder, on my computer, it would fail. Turns out, it (apparently) because Java doesn’t necessarily share my mapped drives. Here’s the code that I used to overcome this:

System.out.println("Try to move file");

// create a net use command to map the drive...
String command = "c:\\windows\\system32\\net.exe use Z: \\\\\\f$";
Process p = Runtime.getRuntime().exec(command);

// create an instance of the file to move
File f=new File(".\\myImage.jpg");

// make sure that the file actually exists
boolean fileExists=f.exists();
System.out.println("File Found");
System.out.println("File Not Found");

//create a random number and timestamp, for a unique file name
Random rand = new Random();
int randNum = rand.nextInt();
Date date=new Date();

// Create the new filename
String newFileName=new String("myImage_"+date.getTime()+"_"+randNum+".jpg");

//try to move the file
boolean moved=f.renameTo(new File("Z:\\Home\\ITS\\sigImages\\"+newFileName));
System.out.println("File moved -> "+newFileName);
System.out.println("File Not moved");
}catch(Exception ex){

I’m sure there is a more elegant way of doing this, that more experienced Java programmers will know. But, I could not find too much out there on the web… Hope this helps someone…