【JAVA IO】_記憶體操作流筆記
本章目標
掌握記憶體操作流的使用
ByteArrayInputStream和ByteArrayOutputStream
之前所講解的程式中,輸出和輸入都是從檔案中來的,當然,也可以將輸出的位置設定在記憶體之上。此時就要使用ByteArrayInputStream、ByteArrayOutputStream來完成輸入、輸出功能了。
ByteArrayInputStream的主要完成將內容寫入到記憶體之中,而
ByteArrayOutputStream主要是將記憶體中的資料輸出。
格式:
public class ByteArrayInputStream extends InputStream
public class ByteArrayOutputStream extends OutputStream
構造方法:
public ByteArrayInputStream(byte[] buf)
下面利用記憶體操作流完成一個大小寫字母轉化的程式
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(); 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(); }catch(IOException e){ e.printStackTrace(); } System.out.println(newStr); }}
如果要想把一個字元變為小寫,可以通過封裝類:Character
實際上此時還可以通過向上轉型的關係為OutputStream或InputStream執行個體化
import java.io.*;public class ByteArrayDemo02{ 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(); 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(); }catch(IOException e){ e.printStackTrace(); } System.out.println(newStr); }}
實際上,以上的操作可以很好的體現對象的多態性,通過執行個體化其子類的不同,完成的功能也不同,也就相當於輸出也就不同,如果是檔案,則使用FileXxx,如果是記憶體,則使用ByteArrayXxx.