【问题标题】:How to move files and directories如何移动文件和目录
【发布时间】:2014-02-25 12:29:05
【问题描述】:

如何将文件和目录移动到 Java 中的另一个目录中?我正在使用这种技术进行复制,但我需要移动

    File srcFile = new File(file.getCanonicalPath());
    String destinationpt = "/home/dev702/Desktop/svn-tempfiles";

    copyFiles(srcFile, new File(destinationpt+File.separator+srcFile.getName()));

【问题讨论】:

标签: java


【解决方案1】:

你可以试试这个:

srcFile.renameTo(new File("C:\\folderB\\" + srcFile.getName()));

【讨论】:

  • 同样我需要同时将一个目录和文件移动到另一个目录
  • 这也可以将文件移动到另一个目录
【解决方案2】:

你读过这个“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]
     }

}

【讨论】:

    【解决方案3】:

    Java.io.File 不包含任何现成的移动文件方法,但您可以使用以下两种替代方法来解决:

    1. File.renameTo()

    2. 复制到新文件并删除原文件。

      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();
            }
        }
    }
    

    希望能帮到你:)

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多