java中的字符流、字节流、缓冲流

来源:互联网 发布:火淘宝挖客专家 编辑:程序博客网 时间:2024/06/06 07:16
package LyfPractice;import org.junit.Test;import java.io.*;import java.text.SimpleDateFormat;import java.util.Scanner;/** * Created by fangjiejie on 2016/12/6. *///硬盘对内存public class File {    public File(String s) {    }   //用字节流读    @Test //单元测试,必须是公有非静态的,必须是没有返回值的,必须是没有形参的才可以用    public  void read(){        //FileInputStream继承了InputStream(抽象类),而InputStream实现了一个借口Closeable        //所以可以尝试利用如下方式,不用写close,而其自动关闭        try(FileInputStream f1=new FileInputStream("D://lyf.txt")){            byte[] buffer=new byte[1024*5];//5k            int n=-1;            //文件流把字节码读入缓存            while((n=f1.read(buffer))!=-1)//每次读取的长度赋值给n            {                 System.out.println(new String(buffer));//以字符串的形式输出,有可能乱码,原因是文件内容的写入并不是本段程序写入的            }        }catch (Exception e){        }finally {        }    }    //用字节流写    @Test    public void write(){        try (FileOutputStream f2=new FileOutputStream("D://lyf.txt",true)){//true所在的参数可写可不写,写上代表追加              f2.write("啦啦啦".getBytes());//要的是byte类型所以得转换一下        }catch (Exception e) {            e.printStackTrace();        }    }    @Test    //用字节流拷贝    public void copy(){//文件拷贝 ---几乎对文件类型无限制        try (FileInputStream f3=new FileInputStream("d://liu.wmv");//创建一个输入流             FileOutputStream f4=new FileOutputStream("e://liu.wmv");//创建一个输出流        ){            int n=1;            long start=System.currentTimeMillis();//计算拷贝时间,date是long 的一种类型            byte[] buffer=new byte[1024*1024*10];            while((n=f3.read(buffer))!=-1){//将f3字节码读入缓存中                f4.write(buffer,0,n);//将缓存中的字节码写入到f4中            }            long last=System.currentTimeMillis();            SimpleDateFormat h=new SimpleDateFormat("mm:ss");            System.out.println(h.format((last-start)));        } catch (Exception e) {            e.printStackTrace();        }    } //利用字符流拷贝:    @Test    public void copy1(){        try (Reader f1=new FileReader("d://lyf.txt");             Writer f2=new FileWriter("e://lyf2.txt");        ){            char []buffer=new char[1024];            int n=-1;            while((n=f1.read(buffer))!=-1){                f2.write(buffer,0,n);            }        } catch (Exception e) {            e.printStackTrace();        }    }    //用字节流和字符流的情况//当一个文件打开后可以阅读不乱码,最好用字符流(也可以用字节流)//当一个文件打开后不可读,为16进制的表达形式的,必须要用字节流    //缓冲流//数据缓冲区//提高了效率    @Test    public void copy2(){        try (BufferedInputStream  f5=new BufferedInputStream(new  FileInputStream("D://liu.wmv"),1024*1024*10);             BufferedOutputStream f6=new BufferedOutputStream(new FileOutputStream("E://u.wmv"),1024*1024*10);        ){            byte []buffer=new byte[1024*1024*10];            int n=-1;            while((n=f5.read(buffer))!=-1){                f6.write(buffer,0,n);            }        } catch (Exception e) {            e.printStackTrace();        } finally {        }    }}
1 0
原创粉丝点击