java.io.File中不包含任何準備化妝移動文件的方法,但你可以用以下兩種方式解決方法:
File.renameTo()
複製到新的文件,並刪除原文件。
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
用於複製和刪除
public class MoveFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");
File bfile =new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}
希望它能幫助:)
可能重複[移動/複製文件中的Java操作](http://stackoverflow.com/questions/300559/move -copy-file-operations-in-java) –
@EelLee其中的一些答案相當過時。 – assylias