版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40178464/article/details/82055944
字符流的由来:字符流读取文字字节数据以后,不直接操作而是先查指定的编码表,获取对应的文字,再对该文字进行操作,简单说字符流就是字节流+编码表。所以对于文字的操作优先使用字符流。
一、利用字符流实现文本文档的拷贝:较标准的异常处理格式
public class CopyFileTest {
private static final int BUFFER_SIZE = 1024;
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("demo.txt");
fw = new FileWriter("demo_copy.txt");
// 创建一个临时容器,用于缓存读取到的字符
char[] buf = new char[BUFFER_SIZE];
// 定义一个变量记录读取到的字符数
int len;
while ((len = fr.read(buf)) != -1) {
fw.write(buf, 0, len);
}
} catch (Exception e) {
throw new RuntimeException("读写失败");
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二、字符流与字节流读取文本文件的耗时比较:
Class TimeCompare{
public static void main(String[] args) throws IOException {
long l1 = System.currentTimeMillis();
characterCopy();
long l2 = System.currentTimeMillis();
System.out.println("字符流耗时:" + (l2 - l1));
l1 = System.currentTimeMillis();
byteCopy();
long l2 = System.currentTimeMillis();
System.out.println("字节流耗时:" + (l2 - l1));
}
/**
* 字符流操作
* @throws IOException
*/
public static void characterCopy() throws IOException {
FileReader fr = new FileReader("demo.txt");
FileWriter fw = new FileWriter("copydemo_1.txt");
int ch;
while ((ch = fr.read()) != -1) {
fw.write(ch);
}
fw.close();
fr.close();
}
/**
* 字节流操作
* @throws IOException
*/
public static void byteCopy() throws IOException {
FileInputStream fis = new FileInputStream("demo.txt");
FileOutputStream fos = new FileOutputStream("democopy_2.txt");
int ch;
while ((ch = fis.read()) != -1) {
fos.write(ch);
}
fos.close();
fis.close();
}
}
结果:
字符流耗时:17
字节流耗时:46
可以看出字符流在操作文本文件的时候效率是较高的。
三、利用缓冲区提高效率
public static void bufferCopy() throws IOException {
long l1 = System.currentTimeMillis();
FileReader fr = new FileReader("demo.txt");
BufferedReader bufr = new BufferedReader(fr);
FileWriter fw = new FileWriter("democopy_3.txt");
BufferedWriter bufw = new BufferedWriter(fw);
String line;
while ((line = bufr.readLine()) != null) {
bufw.write(line);
bufw.newLine();
bufw.flush();
}
bufr.close();
bufw.close();
long l2 = System.currentTimeMillis();
System.out.println("字符流缓冲区耗时:" + (l2 -l1));
}
结果:
字符流缓冲区耗时:9
可以看到利用缓冲区后效率又有所提高。