读书人

Java 资料和流

发布时间: 2012-10-13 11:38:17 作者: rapoo

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("流转化为文件已经结束");

}

}

读书人网 >编程

热点推荐