Java 文件和流

//下面的类里面包含了相互转化的方法:



package com.abin.file.bytes;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class FileToStream {

//文件转化为流
public String FileTurnStream(String path){
String fileByte="";
try{
InputStream in=new FileInputStream(path);
// in.available()返回文件的字节长度
byte[] bytes=new byte[in.available()];
// 将文件中的内容读入到数组中
in.read(bytes);
fileByte=new BASE64Encoder().encode(bytes);

// fileByte=bytes.toString();
in.close();
}catch(Exception e){
e.printStackTrace();
}
return fileByte;
}


public void StreamToFile(String byteto){
String fileName="E:/Emotion/test/varyall.jpg";
try {
byte[] bytes=new BASE64Decoder().decodeBuffer(byteto);
ByteArrayInputStream in=new ByteArrayInputStream(bytes);
byte[] buffer=new byte[1024];
FileOutputStream out=new FileOutputStream(fileName);
int bytesum=0;
int byteread=0;
while((byteread=in.read(buffer))!=-1){
bytesum+=byteread;
out.write(buffer,0,byteread);
out.flush();
}
out.close();

} catch (Exception e) {
// TODO: handle exception
}
}


}








Junit测试类:

package com.abin.file.bytes;

import junit.framework.TestCase;
import sun.misc.BASE64Decoder;

public class TestFileToStream extends TestCase{

public void testStream()throws Exception{
String frompath="E:/Emotion/Photo/abin.jpg";
String bytes=new FileToStream().FileTurnStream(frompath);
System.out.println("文件开始转化为流");
System.out.println("接收到的没有解码字节流:"+bytes);
System.out.println("接收到的解码字节流:"+new BASE64Decoder().decodeBuffer(bytes));
System.out.println("文件转化为流结束");

System.out.println("流开始转化为文件");

new FileToStream().StreamToFile(bytes);

System.out.println("流转化为文件已经结束");

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值