1.字符流对文件的copy
注意:字符流只能对文本文件进行操作,字符类最好用字符流去copy。
package com.yidongxueyuan.Iofile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TextCopyDemo_01 {
public static void main(String[] args) throws IOException {
/**
* 字符流方法
* 1.单个字符copy
* 2.字符数组copy
* 3.高效单字符copy
* 4.高效字符数组copy
* 5.高效字符行copy
*/
copy_01();
copy_02();
copy_03();
copy_04();
copy_05();
}
private static void copy_01() throws IOException
{
FileReader fr = new FileReader("D:\\dn.txt");
FileWriter fw = new FileWriter("E:\\CopyFile\\copy_01.txt");
int num = 0;
long start = System.currentTimeMillis();
while((num=fr.read())!=-1)
{
fw.write(num);
fw.flush();
}
long end = System.currentTimeMillis();
System.out.println("time_01: "+(end-start));
fr.close();
fw.close();
}
private static void copy_02() throws IOException
{
FileReader fr = new FileReader("D:\\dn.txt");
FileWriter fw = new FileWriter("E:\\CopyFile\\copy_02.txt");
int len = 0;
char ch[] = new char[1024];
long start = System.currentTimeMillis();
while((len=fr.read(ch))!=-1)//len是读取的字符数。如果已到达流的末尾,则返回 -1 。
{
// fw.write(ch,0,len);
// fw.write(len);
// fw.write(ch.toString(),0,len);//toString()方法没有被重写
// fw.write(new String(ch),0,len);
fw.write(new String(ch,0,len));//传递一个字符串对象!
fw.flush();
}
long end = System.currentTimeMillis();
System.out.println("time_02: "+(end-start));
fr.close();
fw.close();
}
private static void copy_03() throws IOException
{
BufferedReader bur = new BufferedReader(new FileReader("D:\\dn.txt"));
BufferedWriter buw = new BufferedWriter(new FileWriter("E:\\CopyFile\\copy_03.txt"));
int num = 0;
long start = System.currentTimeMillis();
while((num=bur.read())!=-1)
{
buw.write(num);
buw.flush();
}
long end = System.currentTimeMillis();
System.out.println("time_03: "+(end-start));
bur.close();
buw.close();
}
private static void copy_04() throws IOException
{
BufferedReader bur = new BufferedReader(new FileReader("D:\\dn.txt"));
BufferedWriter buw = new BufferedWriter(new FileWriter("E:\\CopyFile\\copy_04.txt"));
int num = 0;
char ch[] = new char[1024];
long start = System.currentTimeMillis();
while((num=bur.read(ch,0,ch.length))!=-1)//num为读取的字符数,如果已到达流末尾,则返回 -1
{
// buw.write(ch,0,num);
buw.write(new String(ch),0,num);
buw.flush();
}
long end = System.currentTimeMillis();
System.out.println("time_04: &