欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

字节流和字符流

程序员文章站 2024-03-16 11:59:22
...

1、字符集

1.1、字符编码

字节流和字符流

字节流和字符流

1.2、编码encode

getBytes

package CoreJavaColume.Chapter15;

import java.io.UnsupportedEncodingException;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  17:48
 * 编码:字符串---》字节
 */
public class ContentEncode {

    public static void main(String[] args) throws UnsupportedEncodingException {

        String msg = "性命生命使命";
        //编码:获取字节数组
        byte[] datas = msg.getBytes();//默认使用工程字符集 utf-8
        System.out.println(datas.length);

        //编码:其他字符集
        datas = msg.getBytes("UTF-16LE");
        System.out.println(datas.length);

    }
}

1.3、解码decode

package CoreJavaColume.Chapter15;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  17:53
 * 解码: 字节数组---》字符
 */
public class ContentDecode {

    public static void main(String[] args) {
        String msg = "性命生命使命";
        //编码:获取字节数组
        byte[] datas = msg.getBytes();//默认使用工程字符集 utf-8

        //解码
        msg = new String(datas);
        System.out.println(msg);


    }
}

1.4、乱码原因

  1. 字节数不够
  2. 字符集不统一

2、字节流与字符流

底层

字节流和字符流

2.1、IO标准步骤

  1. 确定源
  2. 选择流
  3. 操作:读和写
  4. 释放系统资源

标准

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  20:16
 * 第一个程序:理解操作步骤
 */
public class IOTEST02 {

    public static void main(String[] args)  {

        //1、创建元
        File src = new File("abc.txt");
        InputStream is = null;
        //2、选择流
        try {
            is = new FileInputStream(src);
            //3、操作
            int temp;
            while((temp=is.read())!=-1){
                System.out.println((char)temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源
            try {
                if(is!=null){
                is.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

2.2、文件字节流 FileInputStream和FileOutPutStream

字节流和字符流

分段读取

2.2.1、FileInputStream

  public static void main(String[] args)  {

        //1、创建元
        File src = new File("abc.txt");
        InputStream is = null;
      
        //2、选择流
        try {
            is = new FileInputStream(src);
            //3、操作(分daunt读取)
            byte[] flush = new byte[1024];//缓冲容器
            int len = -1;//接受长度
            while((len=is.read(flush))!=-1){
                //字节数组---》字符串(解码)
                System.out.println(new String(flush,0,len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源
            try {
                if(is!=null){
                is.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

2.2.2、FileOutPutStream

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  20:33
 * 文件字节输出流
 */
public class IOTEST04 {

    public static void main(String[] args) {

        //1、创建源
        File dest = new File("dest");
        //2、选择流
        OutputStream os = null;
        try{
            os=new FileOutputStream(dest);
            //3、操作(写出)
            String msg = "IO is so easy";
            byte[] datas = msg.getBytes();//字符串->字节数组 (编码)
            os.write(datas,0,datas.length);
            os.flush();//刷新数据


        }catch (FileNotFoundException e){

        }catch (IOException E){

        } finally{
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }
}

2.2.3、文件拷贝

字节流和字符流

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  20:46
 * 拷贝文件
 */
public class IOTEST02 {

    public static void main(String[] args)  {

        //1、创建元
        File src = new File("abc.txt");
        File dest = new File("dest");

        //2、选择流
        InputStream is = null;
        OutputStream os = null;

        try {
            is = new FileInputStream(src);
            os=new FileOutputStream(dest);

            //3、操作(分daunt读取)
            byte[] car = new byte[3];//缓冲容器
            int len = -1;//接受长度
            while((len=is.read(car))!=-1){
                //字节数组---》字符串(解码)
                System.out.println(new String(car,0,len));
                //复制
                os.write(car,0,len);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源,先打开的后关闭
            try {
                if(is!=null){
                is.close();}
                
                if(os!=null){
                    osclos
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }



}

2.3、文件字符流FileReader和FileWriter

字节流和字符流

2.3.1、FileReader

public class IOTEST05 {

    public static void main(String[] args)  {

        //1、创建元
        File src = new File("abc.txt");

        //2、选择流
        Reader reader = null;


        try {
            reader = new FileReader(src);


            //3、操作(分daunt读取)
            char[] car = new char[1024];//缓冲容器
            int len = -1;//接受长度
            while((len=reader.read(car))!=-1){
                //字符数组---》字符串(解码)
                System.out.println(new String(car,0,len));

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源
            try {
                if(reader!=null){
                    reader.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

2.3.2、FileWriter

 //1、创建源
        File dest = new File("dest");
        //2、选择流
        Writer writer = null;
        try{
           writer=new FileWriter(dest);
            //3、操作(写出)
            String msg = "手动蝶阀vsdvsv";

            writer.write(msg);
            writer.flush();//刷新数据

2.4、字节数组流ByteArrayInputStream和ByteArrayOutputStream

这里操作的是内存,不同于上面的文件

与电脑内存打交道

字节流和字符流

2.4.1、ByteArrayInputStream

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  21:13
 * 字节数组流 :ByteArrayInputStream
 */
public class IOTEST07 {

    public static void main(String[] args)  {

        //1、创建元
        byte[] src = "talk is cheap,show me the code".getBytes();

        //2、选择流
        InputStream is = null;


        try {
           is = new ByteArrayInputStream(src);

            //3、操作(分daunt读取)
            byte[] car = new byte[5];//缓冲容器
            int len = -1;//接受长度
            while((len=is.read(car))!=-1){
                //字符数组---》字符串(解码)
                System.out.println(new String(car,0,len));

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源
            try {
                if(is!=null){
                    is.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

2.4.2、ByteArrayOutputstream

  1. 创建源:内部维护
  2. 选择流:不关联源
  3. 操作(写出内容)
  4. 释放资源:可以不用
package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/11 0011  21:18
 */
public class IOTEST08 {

    public static void main(String[] args) {

        //1、创建源
        byte[] dest = null;
        //2、选择流(新增方法)
       ByteArrayOutputStream bos = null;
        try{
           bos =new ByteArrayOutputStream();
            //3、操作(写出)
            String msg = "show me the code";

            byte[] datas = msg.getBytes();//字符串----》字节数组(编码)
            bos.write(datas,0,datas.length);
            bos.flush();
            //获取数据
            dest = bos.toByteArray();
            System.out.println(dest.length);

        }catch (FileNotFoundException e){

        }catch (IOException E){

        } finally{
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }
}

3、装饰器模式

[外字节流和字符流

放大声音

package CoreJavaColume.Chapter15;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  17:22
 */
public class DecoratorTest01 {

    public static void main(String[] args) {
        Person p = new Person();
        p.say();

        Amplifier amplifier = new Amplifier(p);
        amplifier.say();
    }
}

interface Say{
    void say();
}

class Person implements Say{

    //属性
    private int voice = 10;

    public int getVoice() {
        return voice;
    }

    public void setVoice(int voice) {
        this.voice = voice;
    }

    @Override
    public void say() {
        System.out.println("人的声音为"+this.getVoice());
    }
}

class Amplifier implements Say{
    private Person p;

    public Amplifier(Person p) {
        this.p = p;
    }

    @Override
    public void say() {
        System.out.println("人的声音为"+p.getVoice()*100);
    }

    public Person getP() {
        return p;
    }

    public void setP(Person p) {
        this.p = p;
    }
}

模拟咖啡

package CoreJavaColume.Chapter15;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  17:27
 * 模拟咖啡:
 * 1、抽象组件:需要装饰的抽象对象(接口或抽象类)
 * 2、具体组件:需要装饰的对象
 * 3、抽象装饰类:包含了对抽象组件的引用以及装饰共有的方法
 * 4、具体装饰类:被装饰的对象
 *
 */
public class DecoratorTest02 {

    public static void main(String[] args) {

        Drink coffee = new Coffee();
        Drink sugar = new Sugar(coffee);
        System.out.println(sugar.info()+"---->"+sugar.cost());

        Drink milk = new Milk(sugar);
        System.out.println(milk.info()+"---->"+milk.cost());




    }
}

interface Drink{
    double cost();//费用
    String info();//说明
}

//具体组件
class Coffee implements Drink{

    private String name = "原味咖啡";


    @Override
    public double cost() {
        return 10;
    }

    @Override
    public String info() {
        return name;
    }
}


//抽象的装饰类
abstract class Decorate implements Drink{
    @Override
    public double cost() {
        return this.drink.cost();
    }

    @Override
    public String info() {
        return this.drink.info();
    }
    //对抽象组件的引用
    private Drink drink;

    public Decorate(Drink drink) {
        this.drink = drink;
    }
}

//具体装饰类
class Milk extends Decorate{

    public Milk(Drink drink) {
        super(drink);
    }

    @Override
    public double cost() {
        return super.cost()*4;
    }

    @Override
    public String info() {
        return super.info()+"加入了牛奶";
    }
}

class Sugar extends  Decorate{


    public Sugar(Drink drink) {
        super(drink);
    }

    @Override
    public double cost() {
        return super.cost()*2;
    }

    @Override
    public String info() {
        return super.info()+"加入了糖";
    }
}



4、字节缓冲流BufferedInputStream和BufferedOutputStream

字节流和字符流

  • 缓冲流提高了性能
  • 底层还是包装了节点流
  • 释放原则从里到外

4.1、BufferedInputStream

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  17:41
 * 加入缓冲流
 */
public class Bufferedtest01 {

    public static void main(String[] args)  {

        //1、创建元
        File src = new File("abc.txt");

        //2、选择流
        InputStream is = null;
        BufferedInputStream bis = null;

        try {
            is = new FileInputStream(src);
            bis = new BufferedInputStream(is);

            //3、操作(分daunt读取)
            byte[] car = new byte[1024];//缓冲容器
            int len = -1;//接受长度
            while((len=is.read(car))!=-1){
                //字节数组---》字符串(解码)
                System.out.println(new String(car,0,len));

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源
            try {
                if(bis!=null){
                    bis.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

4.2、BufferedOutPutStream

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  17:41
 * 加入缓冲流
 */
public class Bufferedtest01 {

    public static void main(String[] args)  {

        //1、创建元
        File dest = new File("123.txt");

        BufferedOutputStream bos = null;

        try {

            bos=new BufferedOutputStream(new FileOutputStream(dest));

            //3、操作(分daunt读取)
            bos.write(12223);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4、释放资源
            try {
                if(bos!=null){
                    bos.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

5、字符缓冲流BufferedReader和BufferedWriter

字节流和字符流

readLine()

6、转换流InputStreamReader和OutputStreamWriter

字节流和字符流

  • 字节流转换为字符流,方便处理
  • 可以指定字符集

6.1、InputStreamReader(解码)

InputStreamReader是从字节流到字符流的桥梁:它读取字节,并使用指定的charset将其解码为字符;

它使用的字符集可以由名称指定,或者接受平台的默认字符集

6.2、OutputStreamWriter(编码)

outputStreamWriter是从字符流到租借流的桥梁

每次调用write()方法都会使编码转换器在给定的字符上被调用。所得到的字节在写入底层输出流之前累积在缓冲区中。

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  18:05
 * 转换流:InputStreamReader OutputStreamWriter
 * 1、以字符流的形式操作字节流
 * 2、指定字符集
 */
public class ConvertTest {

    public static void main(String[] args) {

        //操作System.in和SYS
        try( BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        ) {

            //循环获取键盘的输入
            String msg = "";
            while(!msg.equals("exit")){
                msg=reader.readLine();//循环读取
                writer.write(msg);//循环写出
                writer.newLine();
                writer.flush();
            }



        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

7、数据流 DataInputStream和DataOutputStream

字节流和字符流

package CoreJavaColume.Chapter15;

import java.io.*;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  19:28
 * 数据流
 */
public class DataStreamTest {

    public static void main(String[] args) {

        try(DataOutputStream dos=new DataOutputStream(new FileOutputStream("abc.txt"));
            DataInputStream dis = new DataInputStream(new FileInputStream("abc.txt"))
        ){
            //操作数据类型
            dos.writeUTF("便捷");
            dos.writeInt(18);
            dos.writeChar('a');
            dos.flush();

            String msg = dis.readUTF();
            System.out.println(msg);
            int t = dis.readInt();
            System.out.println(t);
            char s = dis.readChar();
            System.out.println(s);


        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

8、对象流(序列化与反序列化)ObjectInputStream和oBjectOUtputStream

字节流和字符流

不是所有对象都可以序列化:实现Serializable的接口

某些数据不想序列化 transient

package CoreJavaColume.Chapter15;

import java.io.*;
import java.util.Date;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/2/12 0012  19:39
 * 对象流:
 * 1、写出后读取
 * 2、读取的顺序和写出的顺序保持一致
 * 3、不是所有的对象都可以序列化 Serializable
 */
public class ObjectStreamTest {

    public static void main(String[] args) {

        try(ObjectOutputStream dos=new ObjectOutputStream(new FileOutputStream("abc.txt"));
            ObjectInputStream dis = new ObjectInputStream(new FileInputStream("abc.txt"))
        ){
            //操作数据类型
            dos.writeUTF("便捷");
            dos.writeInt(18);
            dos.writeChar('a');

            dos.writeObject(new Date());
            dos.flush();

            String msg = dis.readUTF();
            System.out.println(msg);
            int t = dis.readInt();
            System.out.println(t);
            char s = dis.readChar();
            System.out.println(s);

            Date date = (Date)dis.readObject();//反序列化 
            System.out.println(date);


        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

}

相关标签: Java基础整理