java 流與byte 互相轉換,並與base64編碼轉換


在java 文件操作過程中,經常會用到stream to byte 還有 byte  to stream ,另外如果是用來原創傳輸文件,還必須將流轉換成base64 編碼,然后才好傳輸, 一旦受到這個base64的字符串,接收端,需要將這個還原成流,保存為文件。

下面就是幾個主要方法:

1. streamtobyte:

public static byte[] steamToByte(InputStream input) throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = input.read(b, 0, b.length)) != -1) {                     
            baos.write(b, 0, len);
        }
        byte[] buffer =  baos.toByteArray();
        return buffer;
}

2.bytetostream:

public static final InputStream byteTostream(byte[] buf) {  
        return new ByteArrayInputStream(buf);  
}

3.文件內容base64編碼:

public static String getBase64Content(ContentTransfer content) throws IOException{        
        InputStream inputStream = content.accessContentStream();
        byte[] output = steamToByte(inputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String outstr = encoder.encode(output);
        System.out.println(outstr);
        saveBase64strToFile(outstr);
        return outstr;        
}

 

4. 轉換base64字符串為文件:

public static void saveBase64strToFile(String base64str){
        if (base64str == null){
            return ;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try 
        {           
            byte[] b = decoder.decodeBuffer(base64str);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0){
                    b[i]+=256;
                }
            }            
            String imgFilePath = "c:/base.jpg";//新生成的圖片
            OutputStream out = new FileOutputStream(imgFilePath);    
            out.write(b);
            out.flush();
            out.close();           
        } 
        catch (Exception e){
           e.printStackTrace();
        }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM