【JAVA IO】_記憶體操作流筆記

來源:互聯網
上載者:User

【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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.