![](/img/trans.png)
[英]how to move different sub directories and files in to one directory in java
[英]How to move files and directories
如何將文件和目錄移動到Java中的另一個目錄? 我正在使用此技術進行復制,但是我需要移動 :
File srcFile = new File(file.getCanonicalPath());
String destinationpt = "/home/dev702/Desktop/svn-tempfiles";
copyFiles(srcFile, new File(destinationpt+File.separator+srcFile.getName()));
您可以嘗試以下方法:
srcFile.renameTo(new File("C:\\folderB\\" + srcFile.getName()));
您閱讀過此“ http://java.about.com/od/InputOutput/a/Deleting-Copying-And-Moving-Files.htm ”
Files.move(original, destination, StandardCopyOption.REPLACE_EXISTING)
將文件移到目標位置。
如果要移動目錄,請使用此
File dir = new File("FILEPATH");
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
//move files[i]
}
}
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();
}
}
}
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.