Java程序从字符串/字节数组创建流
创建一个输入流并设置字符串:
DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream("pqrs tu v wxy z".getBytes()));
该getBytes()
方法用于将字符串转换为字节序列并返回字节数组。
现在返回一个输入字节:
(char) inputStream.readByte()
示例
import java.io.ByteArrayInputStream; import java.io.DataInputStream; public class Demo { public static void main(String[] args) throws Exception { DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream("pqrs tu v wxy z".getBytes())); System.out.print((char) inputStream.readByte()); System.out.print((char) inputStream.readByte()); inputStream.close(); } }
输出结果
Pq