java如何拷贝文件到另一个目录下

时间:2024-01-03 18:10:41 买帖  | 投诉/举报

篇首语:本文由小编为大家整理,主要介绍了java如何拷贝文件到另一个目录下相关的知识,希望对你有一定的参考价值。

是将一个文件复制到另一个目录下,不是将一个文件的内容写入另一个文件。

下面列举出4种方式:

1、使用FileStreams复制

这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。正如你所看到的我们执行几个读和写操作try的数据,所以这应该是一个低效率的,下一个方法我们将看到新的方式。 这是第一个方法的代码: 

2、使用FileChannel复制

Java NIO包括transferFrom方法,根据文档应该比文件流复制的速度更快。 这是第二种方法的代码: 

3、使用Commons IO复制

Apache Commons IO提供拷贝文件方法在其FileUtils类,可用于复制一个文件到另一个地方。它非常方便使用Apache Commons FileUtils类时,您已经使用您的项目。基本上,这个类使用Java NIO FileChannel内部。 这是第三种方法的代码: 

4、使用Java7的Files类复制

如果你有一些经验在Java 7中你可能会知道,可以使用复制方法的Files类文件,从一个文件复制到另一个文件。 这是第四个方法的代码: 

参考技术A /**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public void copyFile(String oldPath, String newPath)
try
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1)
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);

inStream.close();


catch (Exception e)
System.out.println("复制单个文件操作出错");
e.printStackTrace();





/**
* 复制整个文件夹内容
* @param oldPath String 原文件路径 如:c:/fqf
* @param newPath String 复制后路径 如:f:/fqf/ff
* @return boolean
*/
public void copyFolder(String oldPath, String newPath)

try
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++)
if(oldPath.endsWith(File.separator))
temp=new File(oldPath+file[i]);

else
temp=new File(oldPath+File.separator+file[i]);


if(temp.isFile())
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ( (len = input.read(b)) != -1)
output.write(b, 0, len);

output.flush();
output.close();
input.close();

if(temp.isDirectory())//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);



catch (Exception e)
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();



本回答被提问者采纳
参考技术B 思路有两个 一个就是读取源文件的内容 输出到新文件的内容 再删除原文件
至于读取的方法 可以到网上搜 有人列出了四种方法
http://blog.csdn.net/ta8210/archive/2008/01/30/2073817.aspx

还有一种方法就是判断操作系统 然后使用系统的命令执行

java 如何把一个目录下的所有.java文件复制到另一个目录下,并保持其结构不变

通过历遍当前文件夹下所有文件和文件夹信息,然后(处理文件夹自己去处理):
File fold = new File( "c:\\test.properties ");
String strNewPath = "c:\\testok\\ ";
File fnewpath = new File(strNewPath);
if(!fnewpath.exists())
fnewpath.mkdirs();
File fnew = new File(strNewPath+fold.getName());
fold.renameTo(fnew);
参考技术A 运用递归可以实现 参考技术B 运用递归的原理 参考技术C 百度上搜索就可以有答案

以上是关于java如何拷贝文件到另一个目录下的主要内容,如果未能解决你的问题,请参考以下文章