Java IO學習筆記(五):記憶體操作流

來源:互聯網
上載者:User
文章目錄
  • ByteArrayInputStream和ByteArrayOutputStream
ByteArrayInputStream和ByteArrayOutputStream

之前所講解的程式中,輸出和輸入都是從檔案中來得,當然,也可以將輸出的位置設定在記憶體之上,此時就要使用ByteArrayInputStream、ByteArrayOutputStream來完成輸入輸出功能了

ByteArrayInputStream的主要功能將內容輸入到記憶體之中

ByteArrayOutputStream的主要功能是將記憶體中的資料輸出

此時應該把記憶體作為操作點


ByteArrayInputStream類的定義:

public class ByteArrayInputStream extends InputStream

構造方法:

public ByteArrayInputStream(byte[] buf)

接受一個byte數組,實際上記憶體的輸入就是在構造方法上將資料傳入到記憶體中。

ByteArrayOutputStream:輸出就是從記憶體中寫出資料

public void write(int b)

 

以下是以記憶體操作流完成的一個大小寫字母轉換的程式:

 1 import java.io.ByteArrayInputStream;
2 import java.io.ByteArrayOutputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6
7 public class Test22 {
8 public static void main(String[] args) throws IOException {
9 String str="HELLO WORlD!!!";
10 InputStream input=new ByteArrayInputStream(str.getBytes());
11 OutputStream output=new ByteArrayOutputStream();
12 int temp=0;
13 while((temp=input.read())!=-1){
14 output.write(Character.toLowerCase(temp));
15 }
16 input.close();
17 output.close();
18 System.out.println(output.toString());
19 }
20 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.