使用Java将文件从一个目录复制到另一个目录

时间:2009-07-17 23:38:43

标签: java file directory copy

我想使用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];

}

32 个答案:

答案 0 :(得分:149)

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

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();
}
来自apache commons-io库的

FileUtils类,自版本1.2起可用。

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

答案 1 :(得分:38)

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

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

答案 2 :(得分:30)

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

Files.copy。

它与O / S本机I / O集成以实现高性能。

有关使用情况的完整说明,请参阅Standard concise way to copy a file in Java?上的A。

答案 3 :(得分:26)

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

答案 4 :(得分:19)

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

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

}

答案 5 :(得分:14)

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

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

    使用copyFileToDirectory(File srcFile, File destDir)

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

    使用copyDirectory(File srcDir, File destDir)

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

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

答案 6 :(得分:11)

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 :(得分:9)

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

答案 8 :(得分:7)

import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);

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

答案 9 :(得分:7)

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

  

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

     

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

     

创建目标目录   如果它不存在。如果   目标目录确实存在,然后   此方法合并源与   目的地,来源   优先级。

你的代码可能像这样简单明了:

File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");

FileUtils.copyDirectory(srcDir, trgDir);

答案 10 :(得分:5)

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

答案 11 :(得分:4)

受到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。

答案 12 :(得分:4)

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

答案 13 :(得分:3)

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

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

答案 14 :(得分:3)

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

答案 15 :(得分:2)

使用

org.apache.commons.io.FileUtils

它非常方便

答案 16 :(得分:2)

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 :(得分:1)

答案 18 :(得分:1)

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

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

答案 19 :(得分:1)

我使用以下代码将上传的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);

答案 20 :(得分:1)

这里只是一个将数据从一个文件夹复制到另一个文件夹的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");
}

}

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

答案 21 :(得分:0)

如果您不想使用外部库,而要使用java.io而不是java.nio类,则可以使用以下简洁方法来复制文件夹及其所有内容:

/**
 * Copies a folder and all its content to another folder. Do not include file separator at the end path of the folder destination.
 * @param folderToCopy The folder and it's content that will be copied
 * @param folderDestination The folder destination
 */
public static void copyFolder(File folderToCopy, File folderDestination) {
    if(!folderDestination.isDirectory() || !folderToCopy.isDirectory())
        throw new IllegalArgumentException("The folderToCopy and folderDestination must be directories");

    folderDestination.mkdirs();

    for(File fileToCopy : folderToCopy.listFiles()) {
        File copiedFile = new File(folderDestination + File.separator + fileToCopy.getName());

        try (FileInputStream fis = new FileInputStream(fileToCopy);
             FileOutputStream fos = new FileOutputStream(copiedFile)) {

            int read;
            byte[] buffer = new byte[512];

            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

答案 22 :(得分:0)

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

    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) {
            }
        }
    }

答案 23 :(得分:0)

我写过递归函数,如果有帮助的话。它会将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();
                }
            }
        }
    }
}

答案 24 :(得分:0)

我提供了一种替代解决方案,而无需使用诸如apache FileUtils之类的第三方。这可以通过命令行完成。

我在Windows上对其进行了测试,并且对我有用。接下来是Linux解决方案。

在这里,我正在使用Windows xcopy命令来复制所有文件,包括子目录。 我传递的参数定义如下。

  • / e-复制所有子目录,即使它们为空。
  • / i-如果Source是目录或包含通配符和Destination 不存在,xcopy假定目标指定目录名称 并创建一个新目录。然后,xcopy复制所有指定的文件 进入新目录。
  • / h-复制具有隐藏文件和系统文件属性的文件。默认情况下, xcopy不会复制隐藏文件或系统文件

我的示例利用ProcessBuilder类构造了一个进程来执行copy(xcopy&cp)命令。

Windows:

String src = "C:\\srcDir";
String dest = "C:\\destDir";
List<String> cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Linux:

String src = "srcDir/";
String dest = "~/destDir/";
List<String> cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

或可以在 Windows Linux 环境中使用的 combo

private static final String OS = System.getProperty("os.name");
private static String src = null;
private static String dest = null;
private static List<String> cmd = null;

public static void main(String[] args) {
    if (OS.toLowerCase().contains("windows")) { // setup WINDOWS environment
        src = "C:\\srcDir";
        dest = "C:\\destDir";
        cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");

        System.out.println("on: " + OS);
    } else if (OS.toLowerCase().contains("linux")){ // setup LINUX environment
        src = "srcDir/";
        dest = "~/destDir/";
        cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);

        System.out.println("on: " + OS);
    }

    try {
        Process proc = new ProcessBuilder(cmd).start();
        BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = null;
        while ((line = inp.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

答案 25 :(得分:0)

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

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

答案 26 :(得分:0)

即使是那么复杂,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); 

就是这样。

<强>参考:

Harold,Elliotte Rusty(2006-05-16)。 Java I / O(p.393)。奥莱利媒体。 Kindle版。

答案 27 :(得分:0)

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 :(得分:0)

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

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) {
    }
}

答案 29 :(得分:0)

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

答案 30 :(得分:0)

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

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

答案 31 :(得分:-3)

你使用renameTo() - 不明显,我知道......但这是Java相当于移动......