您的位置:首页 > 编程语言 > Java开发

Java7中使用try-with-resource语法 实现两种复制文件方法

2016-03-03 19:01 639 查看
在一个工具类中实现两种文件复制方法:

package example.gloryzyf;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class FileUtil {
//工具类中提供的一般都是静态方法 把FileUtil构造私有化 不允许创建工具类的实例
private FileUtil(){
}
//普通IO方式 
public static void copyFile(String res,String dest) throws IOException{
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream(res);
fos=new FileOutputStream(dest);
byte []buffer=new byte[1024];
int bytesToRead;
while((bytesToRead=fis.read(buffer))!=-1){
fos.write(buffer,0,bytesToRead);
}
}finally{
if(fis!=null)
fis.close();
if(fos!=null)
fos.close();
}
}
//使用try-with-resource语法 实现普通IO方式
public static void copyTWRFile(String res,String dest) throws  IOException{
try(FileInputStream fis=new FileInputStream(res)){
try(FileOutputStream fos=new FileOutputStream(dest)){
byte []buffer=new byte[1024];
int bytesToRead;
while((bytesToRead=fis.read(buffer))!=-1){
fos.write(buffer, 0, bytesToRead);
}
}
}
}
//使用try-with-resource语法 实现NIO方式
public static void copyNIOFile(String res,String dest) throws  IOException{
try(FileInputStream fis=new FileInputStream(res)){
try(FileOutputStream fos=new FileOutputStream(dest)){
FileChannel inChannel=fis.getChannel();
FileChannel outChannel=fos.getChannel();
ByteBuffer buffer=ByteBuffer.allocate(1024);
while(inChannel.read(buffer)!=-1){
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: