您的位置:首页 > 运维架构

利用FileChannel复制文件 Copy one File to Another【三种方法】

2009-05-22 13:40 309 查看
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* 复制文件
* @author Administrator
*
*/
public class CopyFile {

public static void main(String[] args) {
try {
// Create channel on the source
FileChannel srcChannel = new FileInputStream("D:\\My Documents\\08-100附件二广州社保培训资料.doc")
.getChannel();
// Create channel on the destination
FileChannel dstChannel = new FileOutputStream("D:\\My Documents\\dstFilename.doc")
.getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

再添两种方法:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

public class FileCopyTest {
public static void main(String[] args) {
//方法一
try {
FileReader fr = new FileReader("c:\\updatedatfix.log");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("c:\\temp2.txt");
PrintWriter pw = new PrintWriter(fw, true);
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}

//方法二

try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:\\updatedatfix.log"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:\\tt.log"));
byte[] buff = new byte[1024];
int len =0;
while((len=bis.read(buff,0,1024))!=-1){
bos.write(buff, 0, len);
}
bis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐