What is InputStream & Output Stream? Why and when do we use them?

前端 未结 8 993
予麋鹿
予麋鹿 2020-11-29 14:09

Someone explain to me what InputStream and OutputStream are?

I am confused about the use cases for both InputStream and

8条回答
  •  清酒与你
    2020-11-29 15:14

    InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources.

    For example, you can write primitive data to a file:

    File file = new File("C:/text.bin");
    file.createNewFile();
    DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
    stream.writeBoolean(true);
    stream.writeInt(1234);
    stream.close();
    

    To read the written contents:

    File file = new File("C:/text.bin");
    DataInputStream stream = new DataInputStream(new FileInputStream(file));
    boolean isTrue = stream.readBoolean();
    int value = stream.readInt();
    stream.close();
    System.out.printlin(isTrue + " " + value);
    

    You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency:

    DataInputStream stream = new DataInputStream(
        new BufferedInputStream(new FileInputStream(file)));
    

    You can write other data such as objects:

    MyClass myObject = new MyClass(); // MyClass have to implement Serializable
    ObjectOutputStream stream = new ObjectOutputStream(
        new FileOutputStream("C:/text.obj"));
    stream.writeObject(myObject);
    stream.close();
    

    You can read from other different input sources:

    byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9};
    DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test));
    int value0 = stream.readInt();
    int value1 = stream.readInt();
    byte value2 = stream.readByte();
    byte value3 = stream.readByte();
    stream.close();
    System.out.println(value0 + " " + value1 + " " + value2 + " " + value3);
    

    For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).

提交回复
热议问题