I'm trying to figure out how to move a file from one directory to another in Java, but can't figure it out.
Can someone provide some suggestions?
Thanks!
Printable View
I'm trying to figure out how to move a file from one directory to another in Java, but can't figure it out.
Can someone provide some suggestions?
Thanks!
This should be what you want. There is no need to create a new file by opening a stream and then copying the contents of the old file into a new file and then have to delete the old file. Also i I just created a new file to work with but you should be working with an exsisting one as it sounds.
Code:import java.io.*;
class G{
public static void main(String[] args){
try{
File source = new File("C:\\Hello.txt");
File dest = new File("C:\\Java\\Hello.txt");
source.createNewFile();
source.renameTo(dest);
}catch(IOException e){;}
}
}
Sorry. Here is a better version of the code that i previously posted. I was in a rush to get to school. :p Since the source file is deleted when the JVM exists you will never see it in the source directory but by looking at the code you can see that it is created and moved into the dest directory providing that it does not already exist in the dest directory.
Code:import java.io.*;
class G{
public static void main(String[] args){
try{
File source = new File("C:" + File.separator + "Hello.txt");
File dest = new File("C:" + File.separator + "Java" + File.separator + "Hello.txt");
File destdir = new File("C:" + File.separator + "Java" + File.separator + "Hello.txt");
source.createNewFile();
source.deleteOnExit();
if(destdir.exists()){
System.out.println(" Unable to move file " + " File exists in dest directory ");
System.exit(0);
}
source.renameTo(dest);
}catch(IOException e){System.err.println(e);}
}
}