BIO编程中的字符流与字节流的常用操作示例及对比

BIO 编程
使用统一接口进行操作,具体实现细节无关
字节流
InputStream OutputStream ,都实现了 Closeable 接口,所以支持 try-resources
InputStream 操作用于实现数据的读取操作
read():int 注意这里只是读取一个字节, 0-255 之间, -1 表示流结束
read(byte[]):int 返回值表示读取的具体字节个数, -1 流结束
close():void 关闭流
另外不重要的方法 read(byte[],int,int) available() skip(long)
练习:读取一个英文的文本文件,并在控制台上输出显示
public class Test2 {
     public static void main(String[] args) { 
            InputStream is = null;
             try {
                    is = new FileInputStream("data/a1.txt"); 
                    int kk = 0; 
                    while (true) { 
                            kk = is.read(); 
                            if (kk == -1) 
                                break; 
                              System.out.print((char) kk); 
    } 
           } catch (FileNotFoundException e) { 
                            System.out.println("文件不存在"); 
                    } catch (IOException e) { 
                            System.out.println("读取出错");
                        } finally {
                     try {
                    if (is != null) is.close(); 
                            } 
                     catch (IOException e) { 
            e.printStackTrace(); 
            }
      } 
}
一次一字节读取数据效率太低,所以引入缓冲数组的方式进行读取
public class Test3 { 
            public static void main(String[] args) throws IOException {
                     try (InputStream is = new FileInputStream("data/a1.txt")) { 
                                byte[] buffer=new byte[8192]; 
                                int len=0; 
                        while((len=is.read(buffer))>0) { 
                                        String ss=new String(buffer,0,len); 
                                        System.out.println(ss);
                 } 
        } 
}
OutputStream 操作方法用于实现数据的写出操作
write(int):void 写出一个字节, int 的低 8
write(byte[] 具体数据, int 起始下标, int 长度 ):void
close():void 关闭流
不重要的方法 write(byte[]) flush()
样例:使用字节流进行文件的拷贝
public class Test4 {
         public static void main(String[] args) { 
                InputStream is = null; 
                OutputStream os = null;
                try {
                    is = new FileInputStream("data/a1.txt"); 
                    File file = new File("out/"); 
                    if(!file.exists()) 
                        file.mkdirs();
                     os=new FileOutputStream("out/a1.bak");//自动创建文件,如果文件已存在 则采用覆盖 
                    int data=0;
                     while((data=is.read())!=-1) { 
                                os.write(data); 
                } 
             } catch (Exception e) { 
            System.out.println(e);
             } finally { 
                try {
                    if (is != null) is.close(); 
                        } catch (IOException e) { 
                        e.printStackTrace(); 
                    }try {
                            if (os != null) os.close(); 
                    } catch (IOException e) {
                             e.printStackTrace();
                         } 
            } 
    }
}
引入缓冲区避免一次一字节的操作,提高执行效率 
public class Test5 { 
            public static void main(String[] args) throws Exception { 
                long start = System.currentTimeMillis(); 
                File dict = new File("out/");
                if (!dict.exists()) 
                    dict.mkdirs();
                 try (InputStream is = new FileInputStream("data/a1.txt"); 
                    OutputStream os = new FileOutputStream("out/a2.bak");) {
                     byte[] buffer = new byte[1024];
                     int len = 0; 
                while ((len = is.read(buffer)) > 0) { 
                os.write(buffer, 0, len); 
                    }
                 }
                long end = System.currentTimeMillis(); 
                System.out.println("执行用时:" + (end - start) + "ms");
     } 
}
字符流
顶级父抽象类 Reader Writer ,一次一字符的操作,实现了 Closeable 接口。如果涉及中文信息,则需 要考虑编码字符集的问题,如果编码字符集错误,则显示乱码
Reader 用于封装字符读取操作
        read():int 返回读取到的字符数据, 0-65535 2B ,返回 -1 表示流末尾
        read(char[]):int 返回读取的字符个数,流结束返回 -1
        close():void 关闭流
Writer用于封装字符写出操作
        write(int):void 写出低 16
        write(char[]数据, int 起始下标, int 写出的字符数 ):void
         close():void 关闭流,释放资源
        write(String):void 写出一个字符串内容到输出流中
样例:从一个txt文件中读取数据,在控制台上显示输出,并写入到指定文件中
public class Test6 { 
            public static void main(String[] args) throws IOException {
             try (Reader in = new FileReader("out/a1.bak");
                 Writer out = new FileWriter("out/aaa.txt");) {
            char[] buffer = new char[1024]; 
            int len = 0; 
            while ((len = in.read(buffer)) > 0) { 
                String ss = new String(buffer, 0, len); 
                System.out.println(ss); 
                out.write(buffer,0,len); 
                //out.write(ss); 
        }
     } 
}
类型

字符流

字节流
文件
FileReader FileWriter
FileInputStream FileOutputStream
数组
CharArrayReader
CharArrayWriter
ByteArrayInputStream
ByteArrayOutputStream
字符串
StringReader StringWriter
线程通讯使用的管道
PipedReader PipeWriter
PipedInputStream PipeOutputStream
 


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值