【问题标题】:How to copy file from one location to another location?如何将文件从一个位置复制到另一个位置?
【发布时间】:2013-05-02 06:49:34
【问题描述】:

我想在 Java 中将文件从一个位置复制到另一个位置。最好的方法是什么?


这是我目前所拥有的:

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
    public static void main(String[] args) {
        File f = new File(
            "D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
        List<String>temp=new ArrayList<String>();
        temp.add(0, "N33");
        temp.add(1, "N1417");
        temp.add(2, "N331");
        File[] matchingFiles = null;
        for(final String temp1: temp){
            matchingFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith(temp1);
                }
            });
            System.out.println("size>>--"+matchingFiles.length);

        }
    }
}

这不会复制文件,最好的方法是什么?

【问题讨论】:

标签: java io


【解决方案1】:

您可以使用 Java 8 Streaming APIPrintWriterFiles API

来实现
try (PrintWriter pw = new PrintWriter(new File("destination-path"), StandardCharsets.UTF_8)) {
    Files.readAllLines(Path.of("src/test/resources/source-file.something"), StandardCharsets.UTF_8)
         .forEach(pw::println);
}

如果您想在复制时即时修改内容,请查看此链接以获取扩展示例 https://overflowed.dev/blog/copy-file-and-modify-with-java-streams/

【讨论】:

  • 这是一种优雅而优雅的方式!
【解决方案2】:

使用流

private static void copyFileUsingStream(File source, File dest) throws IOException {
    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);
        }
    } finally {
        is.close();
        os.close();
    }
}

使用频道

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

使用 Apache Commons IO 库:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

使用 Java SE 7 Files 类:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

或者试试 Googles Guava:

https://github.com/google/guava

文档: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

比较时间:

    File source = new File("/Users/sidikov/tmp/source.avi");
    File dest = new File("/Users/sidikov/tmp/dest.avi");


    //copy file conventional way using Stream
    long start = System.nanoTime();
    copyFileUsingStream(source, dest);
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
     
    //copy files using java.nio FileChannel
    source = new File("/Users/sidikov/tmp/sourceChannel.avi");
    dest = new File("/Users/sidikov/tmp/destChannel.avi");
    start = System.nanoTime();
    copyFileUsingChannel(source, dest);
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
     
    //copy files using apache commons io
    source = new File("/Users/sidikov/tmp/sourceApache.avi");
    dest = new File("/Users/sidikov/tmp/destApache.avi");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
     
    //using Java 7 Files class
    source = new File("/Users/sidikov/tmp/sourceJava7.avi");
    dest = new File("/Users/sidikov/tmp/destJava7.avi");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));

【讨论】:

  • 谢谢,Apache Commons FileUtils 救了我的命,因为我需要构建没有 nio 包的旧 Java 6 项目。 FileUtils.copyFile(...) 甚至比 nio Files.copy(...) 更短/更方便,因为不需要将文件转换为路径。
  • 你也可以试试 Googles guava lib...注意一些不支持 Java 6 的版本 ..我会在接下来的几天更新我的帖子
  • 此答案可以使用更新,因为在 100MiB 文件上,通道复制始终比使用 8、16、32 或 64 KiB 缓冲区(1024 字节缓冲区)的流快 1.5 倍甚至更慢)。
【解决方案3】:

将文件从一个位置复制到另一个位置意味着,需要将整个内容复制到另一个位置。Files.copy(Path source, Path target, CopyOption... options) throws IOException此方法期望源位置是原始文件位置,目标位置是具有相同目标类型的新文件夹位置文件(原样)。 目标位置需要存在于我们的系统中,否则我们需要创建一个文件夹位置,然后在该文件夹位置我们需要创建一个与原始文件名同名的文件。然后使用复制功能,我们可以轻松地从一个位置复制文件给其他人。

 public static void main(String[] args) throws IOException {
                String destFolderPath = "D:/TestFile/abc";
                String fileName = "pqr.xlsx";
                String sourceFilePath= "D:/TestFile/xyz.xlsx";
                File f = new File(destFolderPath);
                if(f.mkdir()){
                    System.out.println("Directory created!!!!");
                }
                else {
                    System.out.println("Directory Exists!!!!");
                }
                f= new File(destFolderPath,fileName);
                if(f.createNewFile())   {

                    System.out.println("File Created!!!!");
                }   else {
                    System.out.println("File exists!!!!");
                }

                Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
                System.out.println("Copy done!!!!!!!!!!!!!!");


            }

【讨论】:

    【解决方案4】:

    Files.exists()

    Files.createDirectory()

    Files.copy()

    覆盖现有文件: 文件.move()

    Files.delete()

    Files.walkFileTree() enter link description here

    【讨论】:

      【解决方案5】:

      在 Java 中使用 New Java File 类 >=7。

      创建以下方法并导入必要的库。

      public static void copyFile( File from, File to ) throws IOException {
          Files.copy( from.toPath(), to.toPath() );
      } 
      

      在main中使用如下创建的方法:

      File dirFrom = new File(fileFrom);
      File dirTo = new File(fileTo);
      
      try {
              copyFile(dirFrom, dirTo);
      } catch (IOException ex) {
              Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
      }
      

      注意:- fileFrom 是您要复制到不同文件夹中的新文件 fileTo 的文件。

      学分 - @Scott:Standard concise way to copy a file in Java?

      【讨论】:

        【解决方案6】:
          public static void copyFile(File oldLocation, File newLocation) throws IOException {
                if ( oldLocation.exists( )) {
                    BufferedInputStream  reader = new BufferedInputStream( new FileInputStream(oldLocation) );
                    BufferedOutputStream  writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
                    try {
                        byte[]  buff = new byte[8192];
                        int numChars;
                        while ( (numChars = reader.read(  buff, 0, buff.length ) ) != -1) {
                            writer.write( buff, 0, numChars );
                        }
                    } catch( IOException ex ) {
                        throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
                    } finally {
                        try {
                            if ( reader != null ){                      
                                writer.close();
                                reader.close();
                            }
                        } catch( IOException ex ){
                            Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() ); 
                        }
                    }
                } else {
                    throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
                }
            }  
        

        【讨论】:

          【解决方案7】:

          您可以使用this(或任何变体):

          Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
          

          另外,我建议使用 File.separator/ 而不是 \\ 以使其兼容多个操作系统,请在此可用的 here 上提问/回答。

          由于您不确定如何临时存储文件,请查看ArrayList

          List<File> files = new ArrayList();
          files.add(foundFile);
          

          要将List 的文件移动到单个目录中:

          List<File> files = ...;
          String path = "C:/destination/";
          for(File file : files) {
              Files.copy(file.toPath(),
                  (new File(path + file.getName())).toPath(),
                  StandardCopyOption.REPLACE_EXISTING);
          }
          

          【讨论】:

          • @vijayk 如果您花时间阅读我建议的链接,您会发现许多有用的想法,例如Walking the File Tree...
          • +1 for Files.copy 但我不同意 File.separator,File 无论如何都会规范路径,所以反斜杠或正斜杠没有区别。
          • @vijayk:您正在使用ArrayList 存储Strings,这是行不通的。您还使用array 来存储文件,但请记住这是一个固定大小,您不能追加 到数组,只能使用可用键(例如myFileArray[0] = new File("");)。
          • @vijayk 我已经扩展了我的答案。
          猜你喜欢
          • 1970-01-01
          • 2015-01-30
          • 1970-01-01
          • 1970-01-01
          • 2019-03-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多