995
技術社區[雲棲]
Java IO--內存操作流ByteArrayInputStream/ByteArrayOutputStream
ByteArrayInputStream和ByteArrayOutputStream

此時操作的時候,應該以內存為操作點。


利用其完成一個大小寫轉換的程序:
import java.io.* ;
public class ByteArrayDemo01{
public static void main(String args[]){
String str = "HELLOWORLD" ; // 定義一個字符串,全部由大寫字母組成
ByteArrayInputStream bis = null ; // 內存輸入流
ByteArrayOutputStream bos = null ; // 內存輸出流
bis = new ByteArrayInputStream(str.getBytes()) ; // 向內存中輸出內容
bos = new ByteArrayOutputStream() ; // 準備從內存ByteArrayInputStream中讀取內容
int temp = 0 ;
while((temp=bis.read())!=-1){
char c = (char) temp ; // 讀取的數字變為字符
bos.write(Character.toLowerCase(c)) ; // 將字符變為小寫
}
// 所有的數據就全部都在ByteArrayOutputStream中
String newStr = bos.toString() ; // 取出內容
try{
bis.close() ;
bos.close() ;
}catch(IOException e){
e.printStackTrace() ;
}
System.out.println(newStr) ;
}
};
總結:
1、內存操作流的操作對象一定是以內存為準,不要以程序為準。
2、實際上此時可以通過向上轉型的關係為OutputStream或InputStream實例化。
2、實際上此時可以通過向上轉型的關係為OutputStream或InputStream實例化。
import java.io.* ;
public class ByteArrayDemo01{
public static void main(String args[]) throws Exception{
String str = "HELLOWORLD" ; // 定義一個字符串,全部由大寫字母組成
InputStream bis = null ; // 內存輸入流
OutputStream bos = null ; // 內存輸出流
bis = new ByteArrayInputStream(str.getBytes()) ; // 向內存中輸出內容
bos = new ByteArrayOutputStream() ; // 準備從內存ByteArrayInputStream中讀取內容
int temp = 0 ;
while((temp=bis.read())!=-1){
char c = (char) temp ; // 讀取的數字變為字符
bos.write(Character.toLowerCase(c)) ; // 將字符變為小寫
}
// 所有的數據就全部都在ByteArrayOutputStream中
String newStr = bos.toString() ; // 取出內容
try{
bis.close() ;
bos.close() ;
}catch(IOException e){
e.printStackTrace() ;
}
System.out.println(newStr) ;
}
};
實際上,以上的操作可以很好的體現對象的多態性,通過實例化其子類的不同,完成的功能也不同,也就相當於輸出位置也就不同。如果是文件,則使用FileXxx,如果是內存,則使用ByteArrayXxx。
最後更新:2017-04-03 14:54:00