InputStrem和OutPutStream分别是什么?应当在什么时候使用它?| Java Debug 笔记

本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>

提问:InputStrem和OutPutStream分别是什么?应当在什么时候使用它?

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

我对InputStreamOutputStream的用例感到困惑。

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

回答一

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

InputStream用于你从中读取的许多内容。

OutputStream用于许多你要写入的内容。

下面是一些示例代码。假设已经创建了InputStream instr和`OutputStream osstr

int i;

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

instr.close();
osstr.close();
复制代码

回答二

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

例如,可以将基本数据写入文件:

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

读取内容

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);
复制代码

你可以使用其他类型的流来增强读/写能力。例如,为了提高效率,可以引入缓冲区:

DataInputStream stream = new DataInputStream(
    new BufferedInputStream(new FileInputStream(file)));
复制代码

可以写入其它数据,例如对象:

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

你可以从不同的输入源中读取:

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);
复制代码

对于大多数输入流,也有一个输出流。你可以定义自己的流来读取/写入特殊的内容。还有用于读取复杂内容的复杂流(例如,有用于读取/写入ZIP格式的流)。

文章翻译自Stack Overflow:stackoverflow.com/questions/1…

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享