复制从一个目录中的文件到另一个在Java中(Copying files from one direc

2019-06-17 11:06发布

我想使用Java从一个目录复制到另一个文件(子目录)。 我有一个目录,目录,用文本文件。 我遍历目录中的第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];

}

Answer 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从类阿帕奇公地IO库,因为1.2版本。

使用的,而不是采用自行编写所有公用事业第三方工具似乎是一个更好的主意。 它可以节省时间和其他宝贵的资源。



Answer 2:

还有就是标准API(还)在任何文件复制方法。 你的选择是:

  • 把它写自己,用一个FileInputStream,一个FileOutputStream和缓冲区从一个复制字节到其他-或者更好的是,使用FileChannel.transferTo()
  • 用户Apache的百科全书文件实用程序
  • 等待NIO2在Java 7中


Answer 3:

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

Files.copy。

它集成了高性能的O / S本地I / O。

见我一个在标准简洁的方式来复制Java中的文件吗? 对于使用的完整描述。



Answer 4:

从下面的例子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();
        }
    }


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

}


Answer 6:

Apache的百科全书文件实用程序是很方便的。 你可以做下面的活动。

  1. 从一个目录到另一个目录拷贝文件。

    使用copyFileToDirectory(File srcFile, File destDir)

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

    使用copyDirectory(File srcDir, File destDir)

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

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



Answer 7:

Spring框架有很多相似的util类,如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);


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


Answer 9:

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

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

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

如果不存在目标目录中创建。 如果目标目录中确实存在,那么这种方法融合了目标的源,与源采取优先次序。

你的代码可能喜欢简单好用的是这样的:

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

FileUtils.copyDirectory(srcDir, trgDir);


Answer 10:

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

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



Answer 11:

Apache的公共文件实用程序就会得心应手,如果你只想要从源移动文件到目标目录,而不是复制整个目录,你可以这样做:

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


Answer 12:

下面是布赖恩的修改代码,拷贝文件从源位置到目标位置。

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


Answer 13:

通过莫希特的回答启发这个线程 。 仅适用于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。



Answer 14:

您可以复制源文件解决方法,以一个新的文件,并删除原。

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


Answer 15:

使用

org.apache.commons.io.FileUtils

它是如此得心应手



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


Answer 17:

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


Answer 18:

该NIO类使这个非常简单。

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



Answer 19:

我用下面的代码到一个上传传输CommonMultipartFile在web应用到一个文件夹,将该文件复制到目标文件夹(IE)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);


Answer 20:

从一个目录复制文件到另一个目录?

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


Answer 21:

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

}

你want..let我这是什么工作代码知道它是否帮助



Answer 22:

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

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


Answer 23:

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


Answer 24:

下面的代码从一个目录复制到另一个文件

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


Answer 25:

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


Answer 26:

甚至没有那么复杂,没有在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); 

而已。

参考:

哈罗德,作者Elliotte生锈(2006-05-16)。 Java的I / O(第393页)。 O'Reilly Media公司。 Kindle版。



Answer 27:

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

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


Answer 28:

下面的递归函数自己编写的,如果它可以帮助任何人。 它将所有文件复制里面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();
                }
            }
        }
    }
}


Answer 29:

如果你不想使用外部库,你要使用的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();
        }


    }
}


Answer 30:

按我的知识,最好的办法如下:

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


文章来源: Copying files from one directory to another in Java