在Java中将文件从一个目录复制到另一个目录

时间:2021-04-10 15:07:59

I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration. In the code, I want to copy the review (which represents the ith text file or review) to trainingDir. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.

我想使用Java将文件从一个目录复制到另一个(子目录)。我有一个目录,dir,包含文本文件。我对dir中的前20个文件进行迭代,并希望将它们复制到dir目录中的另一个目录,这是我在迭代之前创建的。在代码中,我希望将评审(表示第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];

}

29 个解决方案

#1


135  

For now this should solve your problem

现在这应该能解决你的问题

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 class from apache commons-io library, available since version 1.2.

apache common -io库中的FileUtils类,自1.2版本以来可用。

Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.

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

#2


38  

There is no file copy method in the Standard API (yet). Your options are:

在标准API中还没有文件复制方法。你的选择是:

  • Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
  • 自己编写它,使用FileInputStream、FileOutputStream和缓冲区将字节从一个拷贝到另一个——或者更好,使用FileChannel.transferTo()
  • User Apache Commons' FileUtils
  • 用户FileUtils Apache Commons”
  • Wait for NIO2 in Java 7
  • 在Java 7中等待NIO2

#3


28  

In Java 7, there is a standard method to copy files in java:

在Java 7中,有一个标准的方法来复制Java中的文件:

Files.copy.

Files.copy。

It integrates with O/S native I/O for high performance.

它与O/S本机I/O集成以获得高性能。

See my A on Standard concise way to copy a file in Java? for a full description of usage.

看我的A标准简洁的方法在Java中复制一个文件?有关用法的完整描述。

#4


24  

The example below from Java Tips is rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.

下面来自Java技巧的示例非常直接。从那以后,我转向Groovy处理文件系统的操作——更加简单和优雅。但这里是我过去使用的Java技巧。它缺乏必要的健壮的异常处理,以使其简单明了。

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

#5


16  

If you want to copy a file and not move it you can code like this.

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

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

}

#6


14  

apache commons Fileutils is handy. you can do below activities.

apache commons Fileutils非常方便。你可以做下面的活动。

  1. copying file from one directory to another directory.

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

    use copyFileToDirectory(File srcFile, File destDir)

    使用copyFileToDirectory(文件srcFile,文件destDir)

  2. copying directory from one directory to another directory.

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

    use copyDirectory(File srcDir, File destDir)

    使用copyDirectory(文件srcDir, File destDir)

  3. copying contents of one file to another

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

    use static void copyFile(File srcFile, File destFile)

    使用静态void copyFile(File srcFile, File destFile)

#7


6  

You seem to be looking for the simple solution (a good thing). I recommend using Apache Common's FileUtils.copyDirectory:

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

Copies a whole directory to a new location preserving the file dates.

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

This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

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

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

如果目标目录不存在,则创建它。如果目标目录确实存在,那么该方法将源与目标合并,源优先。

Your code could like nice and simple like this:

您的代码可以非常简单,如下所示:

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

FileUtils.copyDirectory(srcDir, trgDir);

#8


6  

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


6  

Spring Framework has many similar util classes like Apache Commons Lang. So there is org.springframework.util.FileSystemUtils

Spring框架有许多类似的util类,如Apache Commons Lang,因此有org.springframe .util. filesystemutils

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

#10


4  

Below is Brian's modified code which copies files from source location to destination location.

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

#11


4  

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

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

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

#12


4  

Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:

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

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

If you want to skip directories, you can do:

如果你想要跳过目录,你可以:

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

#13


3  

You can workaround with copy the source file to a new file and delete the original.

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

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  

Inspired by Mohit's answer in this thread. Applicable only for Java 8.

灵感来自莫希特在这篇文章中的回答。只适用于Java 8。

The following can be used to copy everything recursively from one folder to another:

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

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

Stream-style FTW.

Stream-style增值。

#15


2  

Use

使用

org.apache.commons.io.FileUtils

org.apache.commons.io.FileUtils

It's so handy

它是如此方便

#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  

The NIO classes make this pretty simple.

NIO类使这变得非常简单。

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

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

#18


1  

Copy file from one directory to another directory...

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

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  

here is simply a java code to copy data from one folder to another, you have to just give the input of the source and destination.

这里只是一个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");
}

}

this a working code for what you want..let me know if it helped

这是你想要的工作代码。如果有用就告诉我

#20


0  

i use the following code to transfer a uploaded CommonMultipartFile to a folder and copy that file to a destination folder in webapps (i.e) web project folder,

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

    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


0  

You can use the following code to copy files from one directory to another

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

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

#22


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

#23


0  

following code to copy files from one directory to another

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

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

#24


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

#25


0  

Not even that complicated and no imports required in Java 7:

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

The renameTo( ) method changes the name of a file:

renameTo()方法更改文件的名称:

public boolean renameTo( File destination)

公共布尔renameTo(文件目的地)

For example, to change the name of the file src.txt in the current working directory to dst.txt, you would write:

例如,要更改文件src的名称。当前工作目录中的txt到dst。三,你会写:

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

That's it.

就是这样。

Reference:

参考:

Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.

哈罗德,Elliotte Rusty(2006-05-16)。Java I / O(p。393)。O ' reilly媒体。Kindle版。

#26


0  

You can use the following code to copy files from one directory to another

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

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

#27


0  

Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.

如果我写的递归函数对任何人都有帮助的话。它将把sourcedirectory中的所有文件复制到destinationDirectory。

example:

例子:

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

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

    }

}

#28


0  

Java 8

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

Copy Method

复制方法

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

#29


-3  

you use renameTo() – not obvious, I know ... but it's the Java equivalent of move ...

你用renameTo() -不明显,我知道…但这是Java版的move……

#1


135  

For now this should solve your problem

现在这应该能解决你的问题

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 class from apache commons-io library, available since version 1.2.

apache common -io库中的FileUtils类,自1.2版本以来可用。

Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.

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

#2


38  

There is no file copy method in the Standard API (yet). Your options are:

在标准API中还没有文件复制方法。你的选择是:

  • Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
  • 自己编写它,使用FileInputStream、FileOutputStream和缓冲区将字节从一个拷贝到另一个——或者更好,使用FileChannel.transferTo()
  • User Apache Commons' FileUtils
  • 用户FileUtils Apache Commons”
  • Wait for NIO2 in Java 7
  • 在Java 7中等待NIO2

#3


28  

In Java 7, there is a standard method to copy files in java:

在Java 7中,有一个标准的方法来复制Java中的文件:

Files.copy.

Files.copy。

It integrates with O/S native I/O for high performance.

它与O/S本机I/O集成以获得高性能。

See my A on Standard concise way to copy a file in Java? for a full description of usage.

看我的A标准简洁的方法在Java中复制一个文件?有关用法的完整描述。

#4


24  

The example below from Java Tips is rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.

下面来自Java技巧的示例非常直接。从那以后,我转向Groovy处理文件系统的操作——更加简单和优雅。但这里是我过去使用的Java技巧。它缺乏必要的健壮的异常处理,以使其简单明了。

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

#5


16  

If you want to copy a file and not move it you can code like this.

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

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

}

#6


14  

apache commons Fileutils is handy. you can do below activities.

apache commons Fileutils非常方便。你可以做下面的活动。

  1. copying file from one directory to another directory.

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

    use copyFileToDirectory(File srcFile, File destDir)

    使用copyFileToDirectory(文件srcFile,文件destDir)

  2. copying directory from one directory to another directory.

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

    use copyDirectory(File srcDir, File destDir)

    使用copyDirectory(文件srcDir, File destDir)

  3. copying contents of one file to another

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

    use static void copyFile(File srcFile, File destFile)

    使用静态void copyFile(File srcFile, File destFile)

#7


6  

You seem to be looking for the simple solution (a good thing). I recommend using Apache Common's FileUtils.copyDirectory:

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

Copies a whole directory to a new location preserving the file dates.

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

This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

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

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

如果目标目录不存在,则创建它。如果目标目录确实存在,那么该方法将源与目标合并,源优先。

Your code could like nice and simple like this:

您的代码可以非常简单,如下所示:

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

FileUtils.copyDirectory(srcDir, trgDir);

#8


6  

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


6  

Spring Framework has many similar util classes like Apache Commons Lang. So there is org.springframework.util.FileSystemUtils

Spring框架有许多类似的util类,如Apache Commons Lang,因此有org.springframe .util. filesystemutils

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

#10


4  

Below is Brian's modified code which copies files from source location to destination location.

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

#11


4  

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

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

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

#12


4  

Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:

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

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

If you want to skip directories, you can do:

如果你想要跳过目录,你可以:

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

#13


3  

You can workaround with copy the source file to a new file and delete the original.

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

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  

Inspired by Mohit's answer in this thread. Applicable only for Java 8.

灵感来自莫希特在这篇文章中的回答。只适用于Java 8。

The following can be used to copy everything recursively from one folder to another:

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

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

Stream-style FTW.

Stream-style增值。

#15


2  

Use

使用

org.apache.commons.io.FileUtils

org.apache.commons.io.FileUtils

It's so handy

它是如此方便

#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  

The NIO classes make this pretty simple.

NIO类使这变得非常简单。

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

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

#18


1  

Copy file from one directory to another directory...

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

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  

here is simply a java code to copy data from one folder to another, you have to just give the input of the source and destination.

这里只是一个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");
}

}

this a working code for what you want..let me know if it helped

这是你想要的工作代码。如果有用就告诉我

#20


0  

i use the following code to transfer a uploaded CommonMultipartFile to a folder and copy that file to a destination folder in webapps (i.e) web project folder,

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

    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


0  

You can use the following code to copy files from one directory to another

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

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

#22


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

#23


0  

following code to copy files from one directory to another

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

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

#24


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

#25


0  

Not even that complicated and no imports required in Java 7:

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

The renameTo( ) method changes the name of a file:

renameTo()方法更改文件的名称:

public boolean renameTo( File destination)

公共布尔renameTo(文件目的地)

For example, to change the name of the file src.txt in the current working directory to dst.txt, you would write:

例如,要更改文件src的名称。当前工作目录中的txt到dst。三,你会写:

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

That's it.

就是这样。

Reference:

参考:

Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.

哈罗德,Elliotte Rusty(2006-05-16)。Java I / O(p。393)。O ' reilly媒体。Kindle版。

#26


0  

You can use the following code to copy files from one directory to another

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

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

#27


0  

Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.

如果我写的递归函数对任何人都有帮助的话。它将把sourcedirectory中的所有文件复制到destinationDirectory。

example:

例子:

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

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

    }

}

#28


0  

Java 8

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

Copy Method

复制方法

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

#29


-3  

you use renameTo() – not obvious, I know ... but it's the Java equivalent of move ...

你用renameTo() -不明显,我知道…但这是Java版的move……