内存流(数组流):
把数据先临时存在数组中,待会再从数组中获取出来。
1. 字节内存流:ByteArrayInputStream/ByteArrayOutputStream
2. 字符内存流:CharArrayInputStream/CharArrayOutputStream
3. 字符串流:StringReader/StringWriter(把数据存放在数组中)
字节内存流:
public class ByteArrayDemo { public static void main(java.lang.String[] args) throws Exception { //字节数组输出流:程序到内存 ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write("ABCD".getBytes()); //使用存储的临时数据 byte[] buffer = bos.toByteArray(); //字节数组输入流:内存到程序 ByteArrayInputStream bis = new ByteArrayInputStream(buffer); byte[] bys = new byte[1024]; int len = -1; while ((len = bis.read(bys)) != -1) { System.out.print(new java.lang.String(bys,0,len)); } bos.close(); bis.close(); } }
字符数组流:与字节操作大致相同。
字符串流:
1 public class StringWriterReaderDemo { 2 public static void main(String[] args) throws IOException { 3 //字符串的输出流 4 StringWriter stringWriter = new StringWriter(); 5 stringWriter.write("你多大了?"); 6 stringWriter.write("21岁!"); 7 8 //字符串的输入流 9 StringReader stringReader = new StringReader(stringWriter.toString()); 10 char[] buffer = new char[1024]; 11 int len = -1; 12 while((len = stringReader.read(buffer)) != -1){ 13 System.out.println(new String(buffer,0,len)); 14 } 15 } 16 }
时间: 2024-10-14 17:08:09