【问题标题】:Copying files from one directory to another in Java在Java中将文件从一个目录复制到另一个目录
【发布时间】:2010-11-11 21:09:48
【问题描述】:

我想使用 Java 将文件从一个目录复制到另一个(子目录)。我有一个包含文本文件的目录 dir。我遍历 dir 中的前 20 个文件,并希望将它们复制到 dir 目录中的另一个目录,该目录是我在迭代之前创建的。 在代码中,我想将review(代表第i 个文本文件或评论)复制到trainingDir。我怎样才能做到这一点?似乎没有这样的功能(或者我找不到)。谢谢。

boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
    File review = reviews[i];

}

【问题讨论】:

  • 那么,您有一个充满文件的目录,而您只想复制这些文件?输入端没有递归 - 例如将所有内容从子目录复制到主目录?
  • 是的,完全正确。我对将这些文件复制或移动到另一个目录都感兴趣(尽管在帖子中我只要求复制)。
  • 未来更新。 Java 7 具有来自Files 类的功能来复制文件。这是另一篇关于它的帖子stackoverflow.com/questions/16433915/…

标签: java file directory copy


【解决方案1】:

现在这应该可以解决您的问题

File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
    FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
    e.printStackTrace();
}

FileUtils 类来自 apache commons-io 库,从 1.2 版开始可用。

使用第三方工具而不是自己编写所有实用程序似乎是一个更好的主意。它可以节省时间和其他宝贵的资源。

【讨论】:

  • FileUtils 对我不起作用。我将源设为“E:\\Users\\users.usr”,将目标设为“D:\\users.usr”。可能是什么问题?
  • 不错的解决方案,对我来说,当我将FileUtils.copyDirectory(source,dest) 更改为FileUtils.copyFile(source, dest) 时,它可以工作,如果它不存在则可以创建目录
  • FileUtils.copyDirectory 只复制目录而不是子目录中的文件。 FileUtils.copyDirectoryStructure 复制所有文件和子目录
【解决方案2】:

标准 API 中没有文件复制方法(目前)。您的选择是:

  • 自己编写,使用 FileInputStream、FileOutputStream 和缓冲区将字节从一个复制到另一个 - 或者更好的是,使用 FileChannel.transferTo()
  • 用户 Apache Commons'FileUtils
  • 在 Java 7 中等待 NIO2

【讨论】:

  • +1 for NIO2:这些天我正在试验 NIO2/Java7.. 新的路径设计得非常好
  • 好的,在 Java 7 中怎么做? NIO2 链接现已断开。
  • @ripper234:链接已修复。请注意,我通过在 Google 中输入“java nio2”找到了新链接...
  • 对于 Apache Commons 链接,我认为您的意思是链接到“#copyDirectory(java.io.File, java.io.File)”
【解决方案3】:

在 Java 7 中,一种在 java 中复制文件的标准方法:

Files.copy.

它与 O/S 原生 I/O 集成以实现高性能。

请参阅我在Standard concise way to copy a file in Java? 上的 A 以获取完整的用法说明。

【讨论】:

  • 这并没有解决复制整个目录的问题。
  • 是的...如果您点击链接。不要忘记java中的“File”可以代表一个目录或文件,它只是一个引用。
  • "如果文件是目录,那么它会在目标位置创建一个空目录(目录中的条目不会被复制)"
【解决方案4】:

下面来自Java Tips 的示例相当简单。从那以后,我切换到 Groovy 来处理文件系统的操作——更简单、更优雅。但这是我过去使用的 Java Tips。它缺乏使其万无一失所需的强大异常处理。

 public void copyDirectory(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    }

【讨论】:

  • 谢谢,但我不想复制目录 - 只复制其中的文件。现在我收到错误消息 java.io.FileNotFoundException: (the path to trDir) (Is a directory) 这只是它所说的。我用过这样的方法:copyDirectory(review, trDir);
  • 谢谢,最好检查一下sourceLocation.exists(),以防java.io.FileNotFoundException
【解决方案5】:

如果你想复制一个文件而不是移动它,你可以这样编码。

private static void copyFile(File sourceFile, File destFile)
        throws IOException {
    if (!sourceFile.exists()) {
        return;
    }
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }

}

【讨论】:

  • 嗨,我已经尝试过了,但我收到错误消息: java.io.FileNotFoundException: ...path to trDir... (Is a directory) 我的文件和文件夹中的所有内容似乎都是好的。你知道它出了什么问题,为什么我会得到这个?
  • 但是,在 transferFrom 中是否存在 Windows 错误,无法一次复制大于 64MB 的流? bugs.sun.com/bugdatabase/view_bug.do?bug_id=4938442修复rgagnon.com/javadetails/java-0064.html
  • 我使用的是 Ubuntu 8.10,所以这应该不是问题。
  • 如果你确定你的代码永远不会在不同的平台上运行。
  • @gemm destfile 必须是文件应该复制到的确切路径。这意味着不仅要包含新文件名,还包括要将文件复制到的目录。
【解决方案6】:

Spring Framework 有许多类似的实用程序类,例如 Apache Commons Lang。于是就有了org.springframework.util.FileSystemUtils

File src = new File("/home/user/src");
File dest = new File("/home/user/dest");
FileSystemUtils.copyRecursively(src, dest);

【讨论】:

    【解决方案7】:

    apache commons Fileutils 很方便。 你可以做以下活动。

    1. 将文件从一个目录复制到另一个目录。

      使用copyFileToDirectory(File srcFile, File destDir)

    2. 将目录从一个目录复制到另一个目录。

      使用copyDirectory(File srcDir, File destDir)

    3. 将一个文件的内容复制到另一个文件

      使用static void copyFile(File srcFile, File destFile)

    【讨论】:

      【解决方案8】:
      File sourceFile = new File("C:\\Users\\Demo\\Downloads\\employee\\"+img);
      File destinationFile = new File("\\images\\" + sourceFile.getName());
      
      FileInputStream fileInputStream = new FileInputStream(sourceFile);
      FileOutputStream fileOutputStream = new FileOutputStream(
                      destinationFile);
      
      int bufferSize;
      byte[] bufffer = new byte[512];
      while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
          fileOutputStream.write(bufffer, 0, bufferSize);
      }
      fileInputStream.close();
      fileOutputStream.close();
      

      【讨论】:

      • 干净、简单的答案——没有额外的依赖。
      • 请你描述一下前两行!
      【解决方案9】:

      您似乎正在寻找简单的解决方案(一件好事)。我推荐使用 Apache Common 的 FileUtils.copyDirectory:

      将整个目录复制到新目录 保存文件日期的位置。

      此方法复制指定的 目录及其所有子目录 目录和文件到指定 目的地。目的地是 新的位置和名称 目录。

      目标目录已创建 如果它不存在。如果 目标目录确实存在,那么 此方法将源与 目的地,源头 优先级。

      您的代码可以像这样简单:

      File trgDir = new File("/tmp/myTarget/");
      File srcDir = new File("/tmp/mySource/");
      
      FileUtils.copyDirectory(srcDir, trgDir);
      

      【讨论】:

      • 嗨,我不想复制目录 - 只复制其中的文件。
      • 基本上是一样的,不是吗?源目录中的所有文件都将在目标目录中结束。
      • 这比读取然后写入文件要好得多。 +1
      【解决方案10】:
      import static java.nio.file.StandardCopyOption.*;
      ...
      Files.copy(source, target, REPLACE_EXISTING);
      

      来源:https://docs.oracle.com/javase/tutorial/essential/io/copy.html

      【讨论】:

        【解决方案11】:

        Apache commons FileUtils 会很方便,如果你只想将文件从源目录移动到目标目录而不是复制整个目录,你可以这样做:

        for (File srcFile: srcDir.listFiles()) {
            if (srcFile.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
            } else {
                FileUtils.copyFileToDirectory(srcFile, dstDir);
            }
        }
        

        如果你想跳过目录,你可以这样做:

        for (File srcFile: srcDir.listFiles()) {
            if (!srcFile.isDirectory()) {
                FileUtils.copyFileToDirectory(srcFile, dstDir);
            }
        }
        

        【讨论】:

        • copyFileToDirectory 不会“移动”文件
        【解决方案12】:

        Java 8

        Path sourcepath = Paths.get("C:\\data\\temp\\mydir");
        Path destinationepath = Paths.get("C:\\data\\temp\\destinationDir");        
        Files.walk(sourcepath)
                 .forEach(source -> copy(source, destinationepath.resolve(sourcepath.relativize(source)))); 
        

        复制方法

        static void copy(Path source, Path dest) {
            try {
                Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        

        【讨论】:

          【解决方案13】:

          灵感来自 Mohit 在 this thread 中的回答。仅适用于 Java 8。

          以下内容可用于递归地将所有内容从一个文件夹复制到另一个文件夹:

          public static void main(String[] args) throws IOException {
              Path source = Paths.get("/path/to/source/dir");
              Path destination = Paths.get("/path/to/dest/dir");
          
              List<Path> sources = Files.walk(source).collect(toList());
              List<Path> destinations = sources.stream()
                      .map(source::relativize)
                      .map(destination::resolve)
                      .collect(toList());
          
              for (int i = 0; i < sources.size(); i++) {
                  Files.copy(sources.get(i), destinations.get(i));
              }
          }
          

          流式 FTW。

          2019-06-10 更新:重要说明 - 关闭 Files.walk 调用获取的流(例如,使用 try-with-resource)。感谢@jannis 提出的观点。

          【讨论】:

          • 太棒了!如果有人想复制具有数百万个文件的目录,请使用并行流。我可以轻松显示复制文件的进度,但是在 JAVA 7 nio copyDirectory 命令中,对于大目录,我无法为用户显示进度。
          • 我建议按照the docsyou might get in trouble 中的建议关闭Files.walk(source) 返回的流
          【解决方案14】:

          以下是 Brian 修改后的代码,它将文件从源位置复制到目标位置。

          public class CopyFiles {
           public static void copyFiles(File sourceLocation , File targetLocation)
              throws IOException {
          
                  if (sourceLocation.isDirectory()) {
                      if (!targetLocation.exists()) {
                          targetLocation.mkdir();
                      }
                      File[] files = sourceLocation.listFiles();
                      for(File file:files){
                          InputStream in = new FileInputStream(file);
                          OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName());
          
                          // Copy the bits from input stream to output stream
                          byte[] buf = new byte[1024];
                          int len;
                          while ((len = in.read(buf)) > 0) {
                              out.write(buf, 0, len);
                          }
                          in.close();
                          out.close();
                      }            
                  }
              }
          

          【讨论】:

          • 工作正常,但缺少处理子目录的递归逻辑。我建议做if (file.isDirectory()) { copyFiles(file.getAbsolutePath(), targetLocation.getAbsolutePath() +"/"+file.getName()); } 并将在for-loop 中完成的所有剩余内容放入else-branch
          【解决方案15】:

          您可以将源文件复制到新文件并删除原始文件。

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

          【讨论】:

            【解决方案16】:
            File dir = new File("D:\\mital\\filestore");
            File[] files = dir.listFiles(new File_Filter("*"+ strLine + "*.txt"));
            for (File file : files){    
                System.out.println(file.getName());
            
                try {
                    String sourceFile=dir+"\\"+file.getName();
                    String destinationFile="D:\\mital\\storefile\\"+file.getName();
                    FileInputStream fileInputStream = new FileInputStream(sourceFile);
                    FileOutputStream fileOutputStream = new FileOutputStream(
                                    destinationFile);
                    int bufferSize;
                    byte[] bufffer = new byte[512];
                    while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                        fileOutputStream.write(bufffer, 0, bufferSize);
                    }
                    fileInputStream.close();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            

            【讨论】:

              【解决方案17】:

              防止文件被损坏

              只需下载以下jar!
              Jar File
              Download Page

              import org.springframework.util.FileCopyUtils;
              
              private static void copyFile(File source, File dest) throws IOException {
                  //This is safe and don't corrupt files as FileOutputStream does
                  File src = source;
                  File destination = dest;
                  FileCopyUtils.copy(src, dest);
              }
              

              【讨论】:

                【解决方案18】:

                NIO 类使这变得非常简单。

                http://www.javalobby.org/java/forums/t17036.html

                【讨论】:

                  【解决方案19】:

                  使用

                  org.apache.commons.io.FileUtils

                  很方便

                  【讨论】:

                  • 如果您要发布一个建议库的答案,如果您能真正解释如何使用它而不是仅仅提及它的名称,那就太好了。
                  【解决方案20】:

                  我使用以下代码将上传的CommonMultipartFile 传输到文件夹,并将该文件复制到 webapps(即 Web 项目文件夹)中的目标文件夹,

                      String resourcepath = "C:/resources/images/" + commonsMultipartFile.getOriginalFilename();
                  
                      File file = new File(resourcepath);
                      commonsMultipartFile.transferTo(file);
                  
                      //Copy File to a Destination folder
                      File destinationDir = new File("C:/Tomcat/webapps/myProject/resources/images/");
                      FileUtils.copyFileToDirectory(file, destinationDir);
                  

                  【讨论】:

                    【解决方案21】:

                    将文件从一个目录复制到另一个目录...

                    FileChannel source=new FileInputStream(new File("source file path")).getChannel();
                    FileChannel desti=new FileOutputStream(new File("destination file path")).getChannel();
                    desti.transferFrom(source, 0, source.size());
                    source.close();
                    desti.close();
                    

                    【讨论】:

                      【解决方案22】:

                      这是一个简单的java代码,用于将数据从一个文件夹复制到另一个文件夹,您只需提供源和目标的输入。

                      import java.io.*;
                      
                      public class CopyData {
                      static String source;
                      static String des;
                      
                      static void dr(File fl,boolean first) throws IOException
                      {
                          if(fl.isDirectory())
                          {
                              createDir(fl.getPath(),first);
                              File flist[]=fl.listFiles();
                              for(int i=0;i<flist.length;i++)
                              {
                      
                                  if(flist[i].isDirectory())
                                  {
                                      dr(flist[i],false);
                                  }
                      
                                  else
                                  {
                      
                                      copyData(flist[i].getPath());
                                  }
                              }
                          }
                      
                          else
                          {
                              copyData(fl.getPath());
                          }
                      }
                      
                      private static void copyData(String name) throws IOException {
                      
                              int i;
                              String str=des;
                              for(i=source.length();i<name.length();i++)
                              {
                                  str=str+name.charAt(i);
                              }
                              System.out.println(str);
                              FileInputStream fis=new FileInputStream(name);
                              FileOutputStream fos=new FileOutputStream(str);
                              byte[] buffer = new byte[1024];
                              int noOfBytes = 0;
                               while ((noOfBytes = fis.read(buffer)) != -1) {
                                   fos.write(buffer, 0, noOfBytes);
                               }
                      
                      
                      }
                      
                      private static void createDir(String name, boolean first) {
                      
                          int i;
                      
                          if(first==true)
                          {
                              for(i=name.length()-1;i>0;i--)
                              {
                                  if(name.charAt(i)==92)
                                  {
                                      break;
                                  }
                              }
                      
                              for(;i<name.length();i++)
                              {
                                  des=des+name.charAt(i);
                              }
                          }
                          else
                          {
                              String str=des;
                              for(i=source.length();i<name.length();i++)
                              {
                                  str=str+name.charAt(i);
                              }
                              (new File(str)).mkdirs();
                          }
                      
                      }
                      
                      public static void main(String args[]) throws IOException
                      {
                          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                          System.out.println("program to copy data from source to destination \n");
                          System.out.print("enter source path : ");
                          source=br.readLine();
                          System.out.print("enter destination path : ");
                          des=br.readLine();
                          long startTime = System.currentTimeMillis();
                          dr(new File(source),true);
                          long endTime   = System.currentTimeMillis();
                          long time=endTime-startTime;
                          System.out.println("\n\n Time taken = "+time+" mili sec");
                      }
                      
                      }
                      

                      这是你想要的工作代码。如果有帮助,请告诉我

                      【讨论】:

                      • 您忘记关闭 copyData 中的 FileInputStream 和 FileOutputStream。
                      【解决方案23】:

                      据我所知,最好的方法如下:

                          public static void main(String[] args) {
                      
                          String sourceFolder = "E:\\Source";
                          String targetFolder = "E:\\Target";
                          File sFile = new File(sourceFolder);
                          File[] sourceFiles = sFile.listFiles();
                          for (File fSource : sourceFiles) {
                              File fTarget = new File(new File(targetFolder), fSource.getName());
                              copyFileUsingStream(fSource, fTarget);
                              deleteFiles(fSource);
                          }
                      }
                      
                          private static void deleteFiles(File fSource) {
                              if(fSource.exists()) {
                                  try {
                                      FileUtils.forceDelete(fSource);
                                  } catch (IOException e) {
                                      e.printStackTrace();
                                  }
                              }
                          }
                      
                          private static void copyFileUsingStream(File source, File dest) {
                              InputStream is = null;
                              OutputStream os = null;
                              try {
                                  is = new FileInputStream(source);
                                  os = new FileOutputStream(dest);
                                  byte[] buffer = new byte[1024];
                                  int length;
                                  while ((length = is.read(buffer)) > 0) {
                                      os.write(buffer, 0, length);
                                  }
                              } catch (Exception ex) {
                                  System.out.println("Unable to copy file:" + ex.getMessage());
                              } finally {
                                  try {
                                      is.close();
                                      os.close();
                                  } catch (Exception ex) {
                                  }
                              }
                          }
                      

                      【讨论】:

                        【解决方案24】:

                        您可以使用以下代码将文件从一个目录复制到另一个目录

                        // parent folders of dest must exist before calling this function
                        public static void copyTo( File src, File dest ) throws IOException {
                             // recursively copy all the files of src folder if src is a directory
                             if( src.isDirectory() ) {
                                 // creating parent folders where source files is to be copied
                                 dest.mkdirs();
                                 for( File sourceChild : src.listFiles() ) {
                                     File destChild = new File( dest, sourceChild.getName() );
                                     copyTo( sourceChild, destChild );
                                 }
                             } 
                             // copy the source file
                             else {
                                 InputStream in = new FileInputStream( src );
                                 OutputStream out = new FileOutputStream( dest );
                                 writeThrough( in, out );
                                 in.close();
                                 out.close();
                             }
                         }
                        

                        【讨论】:

                          【解决方案25】:
                              File file = fileChooser.getSelectedFile();
                              String selected = fc.getSelectedFile().getAbsolutePath();
                               File srcDir = new File(selected);
                               FileInputStream fii;
                               FileOutputStream fio;
                              try {
                                   fii = new FileInputStream(srcDir);
                                   fio = new FileOutputStream("C:\\LOvE.txt");
                                   byte [] b=new byte[1024];
                                   int i=0;
                                  try {
                                      while ((fii.read(b)) > 0)
                                      {
                          
                                        System.out.println(b);
                                        fio.write(b);
                                      }
                                      fii.close();
                                      fio.close();
                          

                          【讨论】:

                          • 什么是fileChooser
                          【解决方案26】:

                          以下代码将文件从一个目录复制到另一个目录

                          File destFile = new File(targetDir.getAbsolutePath() + File.separator
                              + file.getName());
                          try {
                            showMessage("Copying " + file.getName());
                            in = new BufferedInputStream(new FileInputStream(file));
                            out = new BufferedOutputStream(new FileOutputStream(destFile));
                            int n;
                            while ((n = in.read()) != -1) {
                              out.write(n);
                            }
                            showMessage("Copied " + file.getName());
                          } catch (Exception e) {
                            showMessage("Cannot copy file " + file.getAbsolutePath());
                          } finally {
                            if (in != null)
                              try {
                                in.close();
                              } catch (Exception e) {
                              }
                            if (out != null)
                              try {
                                out.close();
                              } catch (Exception e) {
                              }
                          }
                          

                          【讨论】:

                            【解决方案27】:
                            import java.io.File;
                            import java.io.FileInputStream;
                            import java.io.FileOutputStream;
                            import java.io.IOException;
                            import java.io.InputStream;
                            import java.io.OutputStream;
                            
                            public class CopyFiles {
                                private File targetFolder;
                                private int noOfFiles;
                                public void copyDirectory(File sourceLocation, String destLocation)
                                        throws IOException {
                                    targetFolder = new File(destLocation);
                                    if (sourceLocation.isDirectory()) {
                                        if (!targetFolder.exists()) {
                                            targetFolder.mkdir();
                                        }
                            
                                        String[] children = sourceLocation.list();
                                        for (int i = 0; i < children.length; i++) {
                                            copyDirectory(new File(sourceLocation, children[i]),
                                                    destLocation);
                            
                                        }
                                    } else {
                            
                                        InputStream in = new FileInputStream(sourceLocation);
                                        OutputStream out = new FileOutputStream(targetFolder + "\\"+ sourceLocation.getName(), true);
                                        System.out.println("Destination Path ::"+targetFolder + "\\"+ sourceLocation.getName());            
                                        // Copy the bits from instream to outstream
                                        byte[] buf = new byte[1024];
                                        int len;
                                        while ((len = in.read(buf)) > 0) {
                                            out.write(buf, 0, len);
                                        }
                                        in.close();
                                        out.close();
                                        noOfFiles++;
                                    }
                                }
                            
                                public static void main(String[] args) throws IOException {
                            
                                    File srcFolder = new File("C:\\sourceLocation\\");
                                    String destFolder = new String("C:\\targetLocation\\");
                                    CopyFiles cf = new CopyFiles();
                                    cf.copyDirectory(srcFolder, destFolder);
                                    System.out.println("No Of Files got Retrieved from Source ::"+cf.noOfFiles);
                                    System.out.println("Successfully Retrieved");
                                }
                            }
                            

                            【讨论】:

                              【解决方案28】:

                              在 Java 7 中甚至没有那么复杂,也不需要导入:

                              renameTo( ) 方法更改文件名:

                              public boolean renameTo( File destination)

                              例如,要将当前工作目录中的文件src.txt 的名称更改为dst.txt,您可以这样写:

                              File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst); 
                              

                              就是这样。

                              参考:

                              哈罗德,艾略特·鲁斯蒂 (2006-05-16)。 Java I/O(第 393 页)。奥莱利媒体。 Kindle版。

                              【讨论】:

                              • 移动不是复制。
                              • 这将移动文件。答案错误!
                              • 如问题的 cmets 中所述,移动将适用于 OP。
                              • 赞成,因为它适合我自己的问题,并且是移动文件最简单的答案。谢谢老兄
                              • 请给出与问题相关的答案
                              【解决方案29】:

                              您可以使用以下代码将文件从一个目录复制到另一个目录

                              public static void copyFile(File sourceFile, File destFile) throws IOException {
                                      InputStream in = null;
                                      OutputStream out = null;
                                      try {
                                          in = new FileInputStream(sourceFile);
                                          out = new FileOutputStream(destFile);
                                          byte[] buffer = new byte[1024];
                                          int length;
                                          while ((length = in.read(buffer)) > 0) {
                                              out.write(buffer, 0, length);
                                          }
                                      } catch(Exception e){
                                          e.printStackTrace();
                                      }
                                      finally {
                                          in.close();
                                          out.close();
                                      }
                                  }
                              

                              【讨论】:

                                【解决方案30】:

                                如果对任何人有帮助,请遵循我编写的递归函数。它会将sourcedirectory中的所有文件复制到destinationDirectory。

                                示例:

                                rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");

                                public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
                                    File file = new File(currentPath);
                                    FileInputStream fi = null;
                                    FileOutputStream fo = null;
                                
                                    if (file.isDirectory()) {
                                        String[] fileFolderNamesArray = file.list();
                                        File folderDes = new File(destinationPath);
                                        if (!folderDes.exists()) {
                                            folderDes.mkdirs();
                                        }
                                
                                        for (String fileFolderName : fileFolderNamesArray) {
                                            rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
                                        }
                                    } else {
                                        try {
                                            File destinationFile = new File(destinationPath);
                                
                                            fi = new FileInputStream(file);
                                            fo = new FileOutputStream(destinationPath);
                                            byte[] buffer = new byte[1024];
                                            int ind = 0;
                                            while ((ind = fi.read(buffer))>0) {
                                                fo.write(buffer, 0, ind);
                                            }
                                        } catch (FileNotFoundException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        } catch (IOException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                        finally {
                                            if (null != fi) {
                                                try {
                                                    fi.close();
                                                } catch (IOException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                            }
                                            if (null != fo) {
                                                try {
                                                    fo.close();
                                                } catch (IOException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                            }
                                        }
                                    }
                                }
                                

                                【讨论】:

                                  猜你喜欢
                                  • 2012-02-15
                                  • 2017-11-18
                                  • 2013-06-01
                                  • 2020-06-22
                                  • 2014-08-12
                                  • 2013-10-24
                                  • 2011-10-24
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多