Java 什么是输入流和输出流?我们为什么以及何时使用它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1830698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:04:35  来源:igfitidea点击:

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

javaioinputstreamoutputstream

提问by Bohemian

Someone explain to me what InputStreamand OutputStreamare?

有人向我解释什么InputStreamOutputStream是谁?

I am confused about the use cases for both InputStreamand OutputStream.

我感到困惑的用例都InputStreamOutputStream

If you could also include a snippet of code to go along with your explanation, that would be great. Thanks!

如果您还可以包含一段代码来配合您的解释,那就太好了。谢谢!

采纳答案by Chip Uni

The goal of InputStreamand OutputStreamis to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn't matter. All that matters is that you receive information from the stream (or send information into that stream.)

InputStreamand的目标OutputStream是抽象不同的输入和输出方式:流是文件、网页还是屏幕都无关紧要。重要的是您从流中接收信息(或将信息发送到该流中。)

InputStreamis used for many things that you read from.

InputStream用于您阅读的许多内容。

OutputStreamis used for many things that you write to.

OutputStream用于您写入的许多内容。

Here's some sample code. It assumes the InputStream instrand OutputStream osstrhave already been created:

这是一些示例代码。它假设InputStream instrOutputStream osstr已经创建:

int i;

while ((i = instr.read()) != -1) {
    osstr.write(i);
}

instr.close();
osstr.close();

回答by pstanton

you read from an InputStream and write to an OutputStream.

您从 InputStream 读取并写入 OutputStream。

for example, say you want to copy a file. You would create a FileInputStream to read from the source file and a FileOutputStream to write to the new file.

例如,假设您要复制一个文件。您将创建一个 FileInputStream 以从源文件中读取,并创建一个 FileOutputStream 以写入新文件。

If your data is a character stream, you could use a FileReader instead of an InputStream and a FileWriter instead of an OutputStream if you prefer.

如果您的数据是字符流,您可以根据需要使用 FileReader 代替 InputStream 和 FileWriter 代替 OutputStream。

InputStream input = ... // many different types
OutputStream output = ... // many different types

byte[] buffer = new byte[1024];
int n = 0;
while ((n = input.read(buffer)) != -1)
    output.write(buffer, 0, n);

input.close();
output.close();

回答by Kaleb Brasee

OutputStream is an abstract class that represents writing output. There are many different OutputStream classes, and they write out to certain things (like the screen, or Files, or byte arrays, or network connections, or etc). InputStream classes access the same things, but they read data in from them.

OutputStream 是一个抽象类,表示写入输出。有许多不同的 OutputStream 类,它们写入某些内容(如屏幕、文件、字节数组、网络连接等)。InputStream 类访问相同的东西,但它们从中读取数据。

Here is a good basic exampleof using FileOutputStream and FileInputStream to write data to a file, then read it back in.

这是一个很好的基本示例,它使用 FileOutputStream 和 FileInputStream 将数据写入文件,然后将其读回。

回答by Arne Deutsch

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.

InputStream 用于读取,OutputStream 用于写入。它们作为装饰器相互连接,以便您可以从所有不同类型的源读取/写入所有不同类型的数据。

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).

对于大多数输入流,也有一个输出流。您可以定义自己的流来读取/写入特殊的东西,并且有用于读取复杂事物的复杂流(例如,有用于读取/写入 ZIP 格式的流)。

回答by Ravindra babu

From the Java Tutorial:

来自Java 教程

A stream is a sequence of data.

流是一个数据序列。

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

程序使用输入流从源读取数据,一次一个项目:

enter image description here

在此处输入图片说明

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

程序使用输出流将数据写入目的地,一次一个项目:

enter image description here

在此处输入图片说明

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 codefrom oracle tutorial:

oracle教程中的示例代码

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.txtfile to outagain.txt, by writing one byte at a time

该程序使用字节流将xanadu.txt文件复制到outagain.txt一次写入一个字节

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

查看此 SE 问题以了解有关高级字符流的更多详细信息,它们是 Byte Streams 之上的包装器:

byte stream and character stream

字节流和字符流

回答by Deep Arora

An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends

输出流通常与一些数据目的地有关,如文件或网络等。在 java 中,输出流是数据最终写入并结束的目的地

import java.io.printstream;

class PPrint {
    static PPrintStream oout = new PPrintStream();
}

class PPrintStream {
    void print(String str) { 
        System.out.println(str)
    }
}

class outputstreamDemo {
    public static void main(String args[]) {
        System.out.println("hello world");
        System.out.prinln("this is output stream demo");
    }
}

回答by Sher Mohammad

Stream: In laymen terms stream is data , most generic stream is binary representation of data.

:在外行术语中,流是数据,最通用的流是数据的二进制表示。

Input Stream: If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

输入流:如果您从文件或任何其他源读取数据,则使用的流是输入流。简单来说,输入流充当读取数据的通道。

Output Stream: If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

输出流:如果要从源(文件等)读取和处理数据,首先需要保存数据,存储数据的意思是输出流。

回答by Jan Bodnar

A stream is a continuous flow of liquid, air, or gas.

流是液体、空气或气体的连续流。

Java stream is a flow of data from a source into a destination. The source or destination can be a disk, memory, socket, or other programs. The data can be bytes, characters, or objects. The same applies for C# or C++ streams. A good metaphor for Java streams is water flowing from a tap into a bathtub and later into a drainage.

Java 流是从源到目的地的数据流。源或目标可以是磁盘、内存、套接字或其他程序。数据可以是字节、字符或对象。这同样适用于 C# 或 C++ 流。Java 流的一个很好的比喻是水从水龙头流入浴缸,然后流入排水管。

The data represents the static part of the stream; the read and write methods the dynamic part of the stream.

数据代表流的静态部分;read 和 write 方法是流的动态部分。

InputStreamrepresents a flow of data from the source, the OutputStreamrepresents a flow of data into the destination. Finally, InputStreamand OutputStreamare abstractions over low-level access to data, such as C file pointers.

InputStream表示来自源OutputStream的数据流, 表示到目的地的数据流。最后,InputStream并且OutputStream是在低级别的访问数据,如C文件指针抽象。