ByteArrayOutputStream和ByteArrayInputStream的简单使用
生活随笔
收集整理的這篇文章主要介紹了
ByteArrayOutputStream和ByteArrayInputStream的简单使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
@ByteArrayOutputStream和ByteArrayInputStream的簡單使用
1.首先看下這兩個IO流是什么?
ByteArrayOutputStream:字節(jié)數(shù)組輸出流.在內(nèi)存中創(chuàng)建一個字節(jié)數(shù)組緩沖區(qū),所有發(fā)送到輸出流的數(shù)據(jù)保存在該字節(jié)數(shù)組緩沖區(qū)中。
ByteArrayInputStream:字節(jié)數(shù)組輸入流.在內(nèi)存中創(chuàng)建一個字節(jié)數(shù)組緩沖區(qū),從輸入流讀取的數(shù)據(jù)保存在該字節(jié)數(shù)組緩沖區(qū)中。
2.java實現(xiàn)文件讀入與寫出:
package com.example.filedemo.demo;import java.io.*;public class ByteArrayIODemo {public static void main(String[] args) {byte[] bytes = ByteArrayOutputStreamDemo();System.out.println(bytes.length); //62230ByteArrayInputStreamDemo(bytes);}//FileInputStream 把文件數(shù)據(jù) 讀入 內(nèi)存//ByteArrayOutputStream 把內(nèi)存中數(shù)據(jù) 讀入 字節(jié)數(shù)組緩沖區(qū)public static byte[] ByteArrayOutputStreamDemo() {byte[] bytes = new byte[1024];int len = -1;//緩沖流提升字節(jié)輸入流效率;try (BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:\\demo\\picture.jpeg"));ByteArrayOutputStream out = new ByteArrayOutputStream()) {while ((len = in.read(bytes)) != -1) {out.write(bytes, 0, len);}return out.toByteArray();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}// ByteArrayInputStream把byte[] 讀入 字節(jié)數(shù)組緩沖區(qū)//FileOutputStream把字節(jié)數(shù)組緩沖區(qū)中數(shù)據(jù)輸出成文件public static void ByteArrayInputStreamDemo(byte[] byteArray) {byte[] bytes = new byte[1024];int len = -1;//try (ByteArrayInputStream in = new ByteArrayInputStream(byteArray);//FileOutputStream 構(gòu)造方法 第二個屬性值 append 為true時,在原有數(shù)據(jù)上追加數(shù)據(jù);append為flase時,覆蓋原有數(shù)據(jù);BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("C:\\demo2\\picture.jpeg", true))) {while ((len = in.read(bytes)) != -1) {out.write(bytes, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }總結(jié)
以上是生活随笔為你收集整理的ByteArrayOutputStream和ByteArrayInputStream的简单使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: element-ui简单使用
- 下一篇: 动态修改网页title