byte array input and output stream

package io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
* 1. File -> Program -> Byte Array
* File Input Stream, Byte Array Output Stream
*
* 2. Byte Array -> Program -> File
* File Output Stream, Byte Array Input Stream
* @author Lenovo
*
*/
public class Text2 {

public static void main(String[] args) throws IOException {
    byte[] str=getbyteformat("D:/src/po.jpg");       
    setbytrform(str,"D:/src/a.jpg");
}
/**
 *  2.字节数组--->程序---->文件
 * 文件输出流,字节数组输入流
 * @param src
 * @param path
 * @throws IOException
 */
public static void setbytrform(byte[] src,String path) throws IOException {
  //创建目的地
  File file1=new File(path);
  //选择流
  InputStream oInputStream=new BufferedInputStream(new ByteArrayInputStream(src));
  OutputStream oStream=new BufferedOutputStream(new FileOutputStream(file1));
  byte[] bt=new byte[1024];
  int len=0;
  while((len=oInputStream.read(bt))!=-1) {
      oStream.write(bt, 0, len);
  }
  oStream.flush();
  oInputStream.close();
  oStream.close();

}       
/**
 * 1.文件--->程序--->字节数组
 * 文件输入流,字节数组输出流
 * @param str
 * @return
 * @throws IOException
 */
public static byte[] getbyteformat(String str) throws IOException {
    //创建文件源
    File file=new File(str);
    //创建字节数组目的地
    byte[] byt=null;
    //选择流
    InputStream stream=new BufferedInputStream(new FileInputStream(file));
    //字节数组输出流 
    ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
    byte[] bete=new byte[1024];
    int len=0;
    while((len=stream.read(bete))!=-1) {
        outputStream.write(bete, 0, len);
    }
    outputStream.flush();
    byt=outputStream.toByteArray();
    stream.close();
    outputStream.close();
    return byt;
}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325950075&siteId=291194637