JAVA--IO(中续)

缓冲区类(高效类)

    字节缓冲输出流
            BufferedOutputStream
    字节缓冲输入流
            BufferedInputStream
public class BufferedOuputStreamDemo1 {
    public static void main(String[] args) throws Exception {
        //BufferedOutputStream(OutputStream out)
        //创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
//        FileOutputStream fos = new FileOutputStream("g.txt");
//        BufferedOutputStream bos = new BufferedOutputStream(fos);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("g.txt"));

        //一次性写一个字节数组
        bos.write("大数据".getBytes());

        bos.close();

    }
}
字节缓冲输入流
    BufferedInputStream
public class BufferedInputStreamDemo1 {
    public static void main(String[] args) throws Exception {
        //BufferedInputStream
        //BufferedInputStream(InputStream in)
        //创建一个 BufferedInputStream并保存其参数,输入流 in ,供以后使用。
//        FileInputStream fis = new FileInputStream("g.txt");
//        BufferedInputStream bis = new BufferedInputStream(fis);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("g.txt"));

        //读取数据
        //一次读取一个字节
//        int b = 0;
//        while ((b=bis.read())!=-1){
//            System.out.print((char) b);
//        }

        System.out.println("======================");

        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = bis.read(bytes)) != -1) {
            System.out.println(new String(bytes, 0, length));
        }

        //释放资源
        bis.close();


    }

}
String(byte[] bytes, Charset charset)
   构造一个新的String由指定用指定的字节的数组解码charset 。解码

 byte[] getBytes(Charset charset)
   使用给定的charset将该String编码为字节序列,将结果存储到新的字节数组中。   编码



编码:把看得懂的变成看不懂的,类似于加密
   String -- byte[]

解码:把看不懂的变成看得懂的,类似于解密
   byte[] -- String
public class StringDemo {
    public static void main(String[] args) throws Exception {
        String s = "你好";

        //String -- byte[]
//        byte[] bytes1 = s.getBytes("GBK");
        System.out.println(bytes1);
//        printArray(bytes1);


        byte[] bytes2 = s.getBytes("Unicode");
        printArray(bytes2);

        System.out.println();

        //byte[] -- String
        String s1 = new String(bytes2, "Unicode");
        System.out.println(s1);


    }

    public static void printArray(byte[] bytes){
        for (byte b : bytes){
            System.out.print(b+",");
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值