如何将文件从一个位置复制到另一个位置?

2022-08-31 11:55:27

我想在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);

        }
    }
}

这不会复制文件,执行此操作的最佳方法是什么?


答案 1

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

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

另外,我建议使用 or 而不是使其在多个操作系统中兼容,请在此处提供对此进行问题/答案。File.separator/\\

由于您不确定如何临时存储文件,请查看: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);
}

答案 2

更新:

另请参见 https://stackoverflow.com/a/67179064/1847899

使用流

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 lib:

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

或者试试谷歌番石榴:

https://github.com/google/guava

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


推荐