将文件从一个目录复制到另一个目录
我想使用Java将文件从一个目录复制到另一个目录(子目录)。我有一个目录,目录,文本文件。我遍历了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];
}
有标准的API(还)在任何文件复制方法。您的选项是:
- 写自己,用一个FileInputStream,一个FileOutputStream和缓冲区从一个复制字节到其他 - 或者更好的是,使用FileChannel.transferTo()
- 用户阿帕奇百科全书FileUtils
- 等待在Java 7中用于NIO2
如果要复制一个文件,而不是移动它,你可以像这样的代码。
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();
}
}
嗨,我已经试过了,但是我得到错误r消息: java.io.FileNotFoundException:... trDir的路径...(是一个目录) 我的文件和文件夹中的所有内容似乎都没问题。你知道它出了什么问题,为什么我得到这个? – user42155 2009-07-18 10:52:22
但是,没有一个Windows错误周围的transferFrom无法复制大于64MB的流在一块? http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4938442修复http://www.rgagnon.com/javadetails/java-0064.html – akarnokd 2009-07-18 12:06:04
我使用Ubuntu 8.10,所以这不应该是问题。 – user42155 2009-07-18 12:18:52
从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();
}
}
现在这应该从apache commons-io库解决您的问题
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
类,因为1.2版本。
使用第三方工具而不是自己编写所有实用程序似乎是一个更好的主意。它可以节省时间和其他有价值的资源。
你似乎在寻找简单的解决方案(一件好事)。我建议使用Apache常见的FileUtils.copyDirectory:
复制整个目录到一个新的 位置保存文件的日期。
此方法将指定的 目录及其所有子目录 复制到指定的 目标。目的地是 新的位置和 目录的名称。
如果目标目录不存在,则创建目标目录 。如果 目标目录确实存在,则 此方法将源与目标 合并,源优先于 。
您的代码可能会喜欢简单好用的是这样的:
File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");
FileUtils.copyDirectory(srcDir, trgDir);
使用
org.apache.commons.io.FileUtils
它是如此的得心应手
下面是布赖恩的修改后的代码从源文件复制位置到目的地的位置。
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();
}
}
}
apache commons Fileutils很方便。 你可以做下面的活动。
-
将文件从一个目录复制到另一个目录。从一个目录到另一个目录
使用
copyFileToDirectory(File srcFile, File destDir)
-
复制目录。
使用
copyDirectory(File srcDir, File destDir)
-
复制一个文件的内容的另一个
使用
static void copyFile(File srcFile, File destFile)
我使用以下代码来一个上传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);
您可以使用下面的代码从一个目录中的文件复制到另一个
// 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();
}
}
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();
}
}
在Java 7,有是在Java中复制文件的标准方法:
文件。复制。
它集成了O/S本机I/O以实现高性能。
有关使用的完整说明,请参阅我的A上的Standard concise way to copy a file in Java?。
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();
下面的代码从一个目录中的文件复制到另一个
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) {
}
}
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的公共文件实用程序就会得心应手,如果你从源只想移动文件到目标目录,而可以这样做:
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);
}
}
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");
}
}
import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);
来源:https://docs.oracle.com/javase/tutorial/essential/io/copy.html
甚至没有那么复杂,并没有在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媒体。 Kindle版。从一个目录到另一个目录
复制文件......
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();
您可以复制源文件解决方法,以一个新的文件,并删除原。
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();
}
}
}
受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。
您可以使用下面的代码从一个目录中的文件复制到另一个
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();
}
}
这里是一个简单的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");
}
}
这是你想要的工作代码..让我知道它是否有帮助
Spring Framework有许多类似的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);
以下递归函数我写了,如果它可以帮助任何人。它会将源目录中的所有文件复制到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();
}
}
}
}
}
因此,你有一个目录充满文件,你想只复制这些文件?在输入端没有递归 - 例如将所有从子目录复制到主目录中? – akarnokd 2009-07-18 12:07:38
是的,确切地说。我感兴趣的只是将这些文件复制或移动到另一个目录(尽管在我刚刚要求复制的文章中)。 – user42155 2009-07-18 12:17:45
来自未来的更新。 Java 7具有来自[Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html)类的功能来复制文件。这是另一篇文章关于它http://stackoverflow.com/questions/16433915/how-to-copy-file-from-one-location-to-another-location – KevinL 2013-10-07 13:19:56