Copying files from one directory to another in Java
我想用Java将文件从一个目录复制到另一个目录(子目录)。我有一个目录dir和文本文件。我迭代dir中的前20个文件,并希望将它们复制到dir目录中的另一个目录,这是我在迭代之前创建的。在代码中,我想将
1 2 3 4 5 6 7 8 9 |
现在这应该能解决你的问题
1 2 3 4 5 6 7 | 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(); } |
ApacheCommonsIO库中的
使用第三方工具而不是自己编写所有实用程序似乎是一个更好的主意。它可以节省时间和其他有价值的资源。
标准API中还没有文件复制方法。您的选择是:
- 自己写,使用一个fileinputstream、一个fileoutputstream和一个缓冲区将字节从一个复制到另一个,或者更好的方法是使用filechannel.transferto()。
- 用户apache commons的fileutils
- 在JAVA 7中等待Ni O2
在Java 7中,有一种在Java中复制文件的标准方法:
拷贝。
它与O/S本机I/O集成以获得高性能。
在Java中用标准简洁的方法复制文件吗?关于用法的完整描述。
下面的例子从Java提示是相当直接的。我已经切换到了groovy来处理文件系统的操作——更加简单和优雅。但这是我过去使用的Java技巧。它缺少使其不易出错所需的强大异常处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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(); } } |
如果你想复制一个文件而不移动它,你可以这样编码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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(); } } |
ApacheCommonsFileUtils很方便。你可以做下面的活动。
正在将文件从一个目录复制到另一个目录。
使用
正在将目录从一个目录复制到另一个目录。
使用
将一个文件的内容复制到另一个文件
使用
Spring框架有许多类似的util类,比如ApacheCommonsLang。
1 2 3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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(); |
你似乎在寻找简单的解决方案(一件好事)。我建议使用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.
您的代码可以像下面这样简单而漂亮:
1 2 3 4 |
1 2 3 | import static java.nio.file.StandardCopyOption.*; ... Files.copy(source, target, REPLACE_EXISTING); |
来源:https://docs.oracle.com/javase/tutorial/essential/io/copy.html
ApacheCommonsFileUtils非常方便,如果您只想将文件从源目录移动到目标目录,而不是复制整个目录,那么可以执行以下操作:
1 2 3 4 5 6 7 | for (File srcFile: srcDir.listFiles()) { if (srcFile.isDirectory()) { FileUtils.copyDirectoryToDirectory(srcFile, dstDir); } else { FileUtils.copyFileToDirectory(srcFile, dstDir); } } |
如果要跳过目录,可以执行以下操作:
1 2 3 4 5 | for (File srcFile: srcDir.listFiles()) { if (!srcFile.isDirectory()) { FileUtils.copyFileToDirectory(srcFile, dstDir); } } |
灵感来自莫希特的回答。仅适用于Java 8。
可以使用以下方法将所有内容从一个文件夹递归复制到另一个文件夹:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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。
下面是Brian修改过的代码,它将文件从源位置复制到目标位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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(); } } } |
您可以将源文件复制到新文件并删除原始文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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(); } } } |
爪哇8
1 2 3 4 | 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)))); |
复制法
1 2 3 4 5 6 7 | static void copy(Path source, Path dest) { try { Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } |
使用
org.apache.commons.io.FileUtils
真是太方便了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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(); } } |
我使用以下代码将上载的
1 2 3 4 5 6 7 8 | 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); |
这里只是一个Java代码,将数据从一个文件夹复制到另一个文件夹,您必须只给出源和目的地的输入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | 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 "); 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(" Time taken ="+time+" mili sec"); } } |
这是一个你想要的工作代码。如果有用的话,请告诉我。
NIO类使这非常简单。
http://www.javalobby.org/java/forums/t17036.html
将文件从一个目录复制到另一个目录…
1 2 3 4 5 | 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(); |
可以使用以下代码将文件从一个目录复制到另一个目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // 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(); } } |
以下代码用于将文件从一个目录复制到另一个目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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) { } } |
据我所知,最好的方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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) { } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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"); } } |
即使在Java 7中也不需要复杂和无需导入:
例如,要将当前工作目录中的文件
就是这样。
参考文献:
Harold,Elliotte Rusty(2006-05-16)。Java I/O(第393页)。O'Reilly媒体。Kindle版本。
可以使用以下代码将文件从一个目录复制到另一个目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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(); } } |
遵循我编写的递归函数,如果它对任何人都有帮助的话。它将把sourceditory中的所有文件复制到destinationdirectory。
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 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(); } } } } } |
如果不想使用外部库,并且想使用java.io而不是java.nio类,可以使用这个简洁的方法复制文件夹及其所有内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /** * 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(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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(); |
你用的是renameto()——不明显,我知道…但它是Java的等效移动…