Java中的InputStreams和OutputStreams

Java读取InputStream到字符串

有时我们可能希望将字节输入读取为字符串。
为此,我们需要找到在字节和“本机Java”UTF-16代码点之间转换的内容,该点用作Char。
使用InputStreamReader完成。

为了加快进程,它是“通常”来分配缓冲区,使得在从输入中读取时我们没有太多开销。

//版本 ≥ Java SE 7
public String inputStreamToString(InputStream inputStream) throws Exception {
     StringWriter writer = new StringWriter();
     char[] buffer = new char[1024];
     try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
        int n;
        while ((n = reader.read(buffer)) != -1) {
              //all this code does is redirect the output of reader to writer in
             //1024 byte chunks
             writer.write(buffer, 0, n);
       }
   }
   return writer.toString();
}

将字节写入OutputStream

一次将字节写入OutputStream一个字节

OutputStream stream = object.getOutputStream();
byte b = 0x00;
stream.write( b );

写一个字节数组

byte[] bytes = new byte[] { 0x00, 0x00 };
stream.write( bytes );

DataInputStream示例

package com.streams;
import java.io.*;
public class DataStreamDemo {
    public static void main(String[] args) throws IOException {
        InputStream input = new    FileInputStream("D:\datastreamdemo.txt");
        DataInputStream inst = new DataInputStream(input);
        int count = input.available();
        byte[] arr = new byte[count];
        inst.read(arr);
        for (byte byt : arr) {
            char ki = (char) byt;
            System.out.print(ki+"-");
        }
    }
}
日期:2020-06-02 22:15:20 来源:oir作者:oir