内存流
什么是内存流
当输出流的目的地,和输入流的源是内存时,这样的流称之为内存流。
常用内存流
- ByteArrayInputStream
- ByteArrayOutputSteam
public class ByteArrayInputStreamDemo {
public static void main(String[] args) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] { 1, 2,
3, 4, 5 });
byte[] bytes = new byte[2];
int len = -1;
while ((len = bais.read(bytes)) != -1) {
for (byte b : bytes) {
System.out.println(b);
}
}
CharArrayReader car = new CharArrayReader(new char[] { 97, 98, 99 });
System.out.println(car.read());
}
}
- CharArrayReader
- CharArrayWriter
public class Demo2 {
public static void main(String[] args) throws IOException {
String s = "你好啊";
char[] cs = s.toCharArray();
CharArrayReader car = new CharArrayReader(cs);
char[] c = new char[1];
int len = -1;
while ((len = car.read(c)) != -1) {
for (char d : c) {
System.out.print(d);
}
}
}
}
- StringReader
- StringWriter
内存流工作模型
打印流
在整个IO包中,打印流是输出信息最方便的类,主要包括字节打印流(PrintStream)和字符打印流(PrintWriter)。打印流提供了非常方便的打印功能,可以打印任何的数据类型。如:小数、整数、字符串等。
PrintStream和PrintWriter都属于输出流,分别针对输出字节和字符。
PrintStream和PrintWriter提供了重载的print()、println()方法用于多种数据类型的输出。
PrintStream和PrintWriter不会抛出异常,用户通过检测错误状态获取错误信息。
PrintStream和PrintWriter有自动flush 功能。
PrintStream
PrintStream(OutputStream out)
PrintStream(OutputStream out, boolean auotflush)
PrintStream(OutputStream out, boolean auotflush, String encoding)PrintWrite
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoflush)
PrintWriter(Writer out)
PrintWriter(Writer out, boolean autoflush)