使用Java语言如何实现快速文件复制

Python08

使用Java语言如何实现快速文件复制,第1张

使用Java语言如何实现快速文件复制:

代码:

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) + "毫秒。")

}

}

import java.io.File\x0d\x0aimport java.io.FileInputStream\x0d\x0aimport java.io.FileNotFoundException\x0d\x0aimport java.io.FileOutputStream\x0d\x0aimport java.io.IOException\x0d\x0apublic class Copy {\x0d\x0a/**\x0d\x0a* @param args\x0d\x0a*/\x0d\x0apublic static void main(String[] args) {\x0d\x0a// TODO Auto-generated method stub\x0d\x0aif(args.length!=2){\x0d\x0aSystem.out.print("没有输入正确数目的参数,程序退出!")\x0d\x0aSystem.exit(0)\x0d\x0a}\x0d\x0aFile fileS = new File("./"+args[0])\x0d\x0aFile fileD = new File("./"+args[1])\x0d\x0aif(fileD.exists())System.out.println("目标文件 "+args[1]+" 已存在!")\x0d\x0abyte[] temp = new byte[50]\x0d\x0aint totalSize = 0\x0d\x0atry {\x0d\x0aFileInputStream fr = new FileInputStream(fileS)\x0d\x0aFileOutputStream fo = new FileOutputStream(fileD)\x0d\x0aint length = 0\x0d\x0awhile((length = fr.read(temp, 0, temp.length)) != -1){\x0d\x0atotalSize += length\x0d\x0afo.write(temp, 0, length)\x0d\x0a}\x0d\x0aSystem.out.println("文件 "+args[0]+" 有 "+totalSize+" 个字节")\x0d\x0aSystem.out.println("复制完成!")\x0d\x0a} catch (FileNotFoundException e) {\x0d\x0a// TODO Auto-generated catch block\x0d\x0ae.printStackTrace()\x0d\x0aSystem.out.println("源文件 "+args[0]+" 不存在!")\x0d\x0a} catch (IOException e) {\x0d\x0a// TODO Auto-generated catch block\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a}\x0d\x0a}