您的位置:首页 > 其它

(六)两种方式将一个文件的内容复制到另一个文件(第二种方式效率更高,第一种一个字符一个字符的读写,第二种一个数组一个数组的读写)

2014-11-15 14:24 537 查看
一:将一个文件复制给另一个文件,每次读取一个字符
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;

public class CopyFile {

/**
* 需求:将一个文件复制给另一个文件
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

//读取一个已有的文件
FileReader fr = new FileReader("D:\\log.txt");

//创建一个目的用于存储读到的数据
FileWriter fw = new FileWriter("D:\\fuyanan.txt");

//频繁的读取数据,每次读取一个字符
int ch = fr.read();
while((ch = fr.read() )!= -1){
fw.write(ch);
}

//关闭数据流
fw.close();
fr.close();

}

}


二、将一个文件复制到另一个文件,每次读取buf个长度

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFile2 {

private static final int BUFFER_SIZE = 1024;

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("D:\\log.txt");
fw = new FileWriter("D:\\fuluolin.txt");

// 创建一个临时容器,用于缓存读取到的字符
char[] buf = new char[BUFFER_SIZE];

// 定义一个变量记录读取到的字符数,(其实就是往数组里装字符)
int len = 0;

while ((len = fr.read(buf)) != -1) {
fw.write(buf, 0, len);
}

} catch (Exception e) {
throw new RuntimeException("读写失败");
} finally {

if (fw != null)
fw.close();
if (fr != null)
fr.close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐