字符流和字节流复制文件的9种方法及测试效率
一、字符流字节流区别:
操作的单位不一样,一个是字节[byte-8bit],一个是字符[变长字节]
操作中文的时候使用字符流更方便 字节流更广泛:文本,视频,音频,图片…
使用缓冲Buffer以后:效率明显提高
二、9种方法
public class java_IO {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
long start=System.currentTimeMillis();//系统当前时间
long end=System.currentTimeMillis();
System.out.println("所用时间:"+(end-start)+"ms");
}
//1.1字符流读写复制文件,每次复制一个字符:-------所用时间:21360ms
public static void copyFileChar(){
System.out.println("请输入你需要拷贝的文件路径:");
String oldPath = sc.next();
System.out.println("请输入你拷贝到的文件路径:");
String newPath = sc.next();
FileReader fileReader = null;
FileWriter fileWriter = null;
try{
fileReader = new FileReader(oldPath);
fileWriter = new FileWriter(newPath);
int red;
while((red = fileReader.read()) != -1){//读取单个字符,-1代表已达到流的末尾
fileWriter.write(red);//写入单个字符
}
System.out.println(oldPath+"文件拷贝完毕!");
fileWriter.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != fileReader){
try{
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != fileWriter){
try{
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//2.2字符流读写复制文件,每次复制一个字符数组:----所用时间:10534ms
public static void copyFileReaderArray(){
System.out.println("请输入你需要拷贝的文件路径:");
String oldPath = sc.next();
System.out.println("请输入你拷贝到的文件路径:");
String newPath = sc.next();
FileReader Reader = null;
FileWriter Writer = null;
try{
Reader = new FileReader(oldPath);
Writer = new FileWriter(newPath);
char[] charArray = new char[1024];//缓冲数组
int readLength;//每次读取的长度
while((readLength = Reader.read(charArray)) != -1){
Writer.write(charArray,0,readLength);//写入读取的字符数组.
}
Writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != Reader){
try{
Reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != Writer){
try{
Writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//3.3缓冲字符流读写复制文件,每次复制复制一个字符:---所用时间:22119ms
public static void copyFileBufferedReaderChar(){
System.out.println("请输入你需要拷贝的文件路径:");
String oldpath=sc.next();
System.out.println("请输入你拷贝到的文件路径:");
String newpath=sc.next();
FileReader Reader = null;
FileWriter Writ