代码:
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.channels.FileChannel
public class Test {
public static void main(String[] args){
long start = System.currentTimeMillis()
FileInputStream fileInputStream = null
FileOutputStream fileOutputStream = null
FileChannel inFileChannel = null
FileChannel outFileChannel = null
try {
fileInputStream = new FileInputStream(new File("C:\\信郑from\\不是闹着玩的.flv"))
fileOutputStream = new FileOutputStream(new File("C:\\to\\不是闹着玩的.flv"))
inFileChannel = fileInputStream.getChannel()
outFileChannel = fileOutputStream.getChannel()
inFileChannel.transferTo(0, inFileChannel.size(), outFileChannel)//连接两个通道,从in通带坦此道读取数据写入out通道。
} catch (IOException e) {
e.printStackTrace()
} finally {
try {
if(fileInputStream != null){
fileInputStream.close()
}
if(inFileChannel != null){
inFileChannel.close()
}
if(fileOutputStream != null){
fileOutputStream.close()
}
if(outFileChannel != null){
outFileChannel.close()
}
} catch (IOException e) {
e.printStackTrace()
}
}
long end = System.currentTimeMillis()
System.out.println("视频文件从“from”文件夹复制到“to”文件需要" + (end - start) + "毫秒。")
}
}
在Java编程中,复制文件的方法有很多,而且经常要用到。我以前一直是缓冲输入输出流来实现的(绝大多数人都是如此),近来在研究JDK文档时发现,用文件通道(蠢族FileChannel)来实现文件复制竟然比用老方法快了近三分之一。下面我就来介绍一下如何用文件通道来实现文件复制,以及在效率上的对比用文件通道的方式来进岁档行乎哗行文件复制
/**
* 使用文件通道的方式复制文件
*
* @param s
*源文件
* @param t
*复制到的新文件
*/
public void fileChannelCopy(File s, File t) {
FileInputStream fi = null
FileOutputStream fo = null
FileChannel in = null
FileChannel out = null
try {
fi = new FileInputStream(s)
fo = new FileOutputStream(t)
in = fi.getChannel()//得到对应的文件通道
out = fo.getChannel()//得到对应的文件通道
in.transferTo(0, in.size(), out)//连接两个通道,并且从in通道读取,然后写入out通道
} catch (IOException e) {
e.printStackTrace()
} finally {
try {
fi.close()
in.close()
fo.close()
out.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)