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

前端 未结 8 989
予麋鹿
予麋鹿 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

    From the Java Tutorial:

    A stream is a sequence of data.

    A program uses an input stream to read data from a source, one item at a time:

    A program uses an output stream to write data to a destination, one item at time:

    The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.

    Sample code from oracle tutorial:

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class CopyBytes {
        public static void main(String[] args) throws IOException {
    
            FileInputStream in = null;
            FileOutputStream out = null;
    
            try {
                in = new FileInputStream("xanadu.txt");
                out = new FileOutputStream("outagain.txt");
                int c;
    
                while ((c = in.read()) != -1) {
                    out.write(c);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        }
    }
    

    This program uses byte streams to copy xanadu.txt file to outagain.txt , by writing one byte at a time

    Have a look at this SE question to know more details about advanced Character streams, which are wrappers on top of Byte Streams :

    byte stream and character stream

提交回复
热议问题