byte[]和InputStream的相互轉換

1:byte[]轉換爲InputStream 
InputStream sbs = new ByteArrayInputStream(byte[] buf); 

2:InputStream轉換爲InputStreambyte[] 
ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
byte[] buff = new byte[100]; //buff用於存放循環讀取的臨時數據 
int rc = 0; 
while ((rc = inStream.read(buff, 0, 100)) > 0) { 
swapStream.write(buff, 0, rc); 
} 
byte[] in_b = swapStream.toByteArray(); //in_b爲轉換之後的結果 

Java代碼  
import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
  
public class ByteToInputStream {  
  
    public static final InputStream byte2Input(byte[] buf) {  
        return new ByteArrayInputStream(buf);  
    }  
  
    public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
  
}


3、InputStream轉換爲byte[]
public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        copy(input, output);
        return output.toByteArray();
    }


public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }

copyLarge()方法不知道引用的那個jar包還是自己寫的方法,測試報錯。下面提供一個java.io.*的方法,已經測試通過:

            try {
<span style="white-space:pre">			</span>FileInputStream inputStream = new FileInputStream(file);
<span style="white-space:pre">			</span>byte[] fileContent = new byte[inputStream.available()];//構建了一個固定長度的byte[]
<span style="white-space:pre">			</span>ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
<span style="white-space:pre">			</span>int rc = 0;
<span style="white-space:pre">			</span>while ((rc = inputStream.read(fileContent, 0, inputStream.available())) > 0) {
<span style="white-space:pre">				</span>swapStream.write(fileContent, 0, rc);
<span style="white-space:pre">			</span>}
<span style="white-space:pre">			</span>byte[] in2b = swapStream.toByteArray();//這裏的byte[]就是實際需要的
<span style="white-space:pre">			</span>edocBarcodeBean.setFileContent(in2b);
<span style="white-space:pre">			</span>file.delete();
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">		</span>}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章