您的位置 首页 java

JAVA之道丨文件复制的四种方法

package test;

import java. io .BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io. file ;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.channels.FileChannel;

import java.nio.file.Files;

import org.apache.commons.io.FileUtils;

/**

* 复制文件的四种方法

* @author </strong>

*

*/

public class IOCopyfile {

/**

* java.io.FileInputStream;

* @param source

* @param dest

* @throws IOException

*/

private static void copyfileusefilestream(File source,File dest) throws IOException {

FileInputStream in=null;

FileOutputStream out=null;

try {

in=new FileInputStream(source);

out=new FileOutputStream(dest);

/*BufferedInputStream bi=new BufferedInputStream(in);//处理输入流-缓冲流 套接文件流

BufferedOutputStream bo=new BufferedOutputStream(out);//处理输出流-缓冲流*/

byte [] buff=new byte[1024];//输入流前 缓存 容器

int read=in.read(buff);//输入流读缓存中的

while(read>0) {

out.write(buff, 0, read);//输出流 写

}

}finally {

out. close ();

in.close();

}

}

/**

* java.nio.channels.FileChannel;

* @param source

* @param dest

* @throws IOException

*/

private static void copyfileusefilechannels(File source,File dest) throws IOException {

FileChannel in=null;

FileChannel out=null;

try {

in=new FileInputStream(source).getChannel();

out=new FileInputStream(dest).getChannel();

out.transferFrom(in, 0, in.size());

} finally {

out.close();

in.close();

}

}

/**

* java.nio.file.Files;

* @param source

* @param dest

* @throws IOException

*/

private static void copyfileusejava7(File source,File dest) throws IOException {

Files.copy(source.toPath(), dest.toPath());

}

/**导入commons-io-xx.jar

* 使用 org .apache.commons.io.FileUtils;基于java.nio.channels.FileChannel

* @param source

* @param dest

* @throws IOException

*/

private static void copyfileusecommonsIO(File source,File dest) throws IOException {

FileUtils.copyFile(source, dest);

}

/**

* 测试

* @param args

* @throws IOException

*/

public static void main(String[] args) throws IOException {

File srcFile=new File(“c:\”);

File desFile=new File(“d:\”);

System.out.println(System.currentTimeMillis()/*System.nanoTime()*/);//复制文件开始时间

IOCopyfile.copyfileusefilestream(srcFile, desFile);

/*IOCopyfile.copyfileusefilechannels(srcFile, desFile);

IOCopyfile.copyfileusejava7(srcFile, desFile);

IOCopyfile.copyfileusecommonsIO(srcFile, desFile);*/

System.out.println(System.currentTimeMillis()/*System.nanoTime()*/);//复制文件结束时间

}

}

文章来源:智云一二三科技

文章标题:JAVA之道丨文件复制的四种方法

文章地址:https://www.zhihuclub.com/174424.shtml

关于作者: 智云科技

热门文章

网站地图