java 流与byte 互相转换,并与base64编码转换
By:Roy.LiuLast updated:2013-07-28
在java 文件操作过程中,经常会用到stream to byte 还有 byte to stream ,另外如果是用来原创传输文件,还必须将流转换成base64 编码,然后才好传输, 一旦受到这个base64的字符串,接收端,需要将这个还原成流,保存为文件。
下面就是几个主要方法:
1. streamtobyte:
2.bytetostream:
3.文件内容base64编码:
4. 转换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
From:一号门
Previous:SPRING DATA JPA 中几种缓存的配置

COMMENTS