內存操作流是以內存作爲操作終端實現的IO數據處理,與文件操作不同的地方在於,內存流不會進行磁盤數據操作,Java中提供有兩類內存操作流:
- 字節內存操作流:ByteArrayOutputStream、ByteArrayInputStream
- 字符內存操作流:CharArrayWriter、CharArrayReader
字節內存操作流
字符內存操作流
範例:利用內存流實現一個小寫字母轉大寫字母的操作
package com.lxh.sixteenchapter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class JavaIODemo417 {
public static void main(String[] args) {
String str="qwertyuiop";
InputStream in=new ByteArrayInputStream(str.getBytes()); //數據保存在內存輸入流
OutputStream out=new ByteArrayOutputStream();
int data=0;
try {
while((data=in.read())!=-1) {
out.write(Character.toUpperCase(data));
}
System.out.println(out);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
執行結果
QWERTYUIOP