java 中 byte[]、File、InputStream 互相转换

1、将File、FileInputStream 转换为byte数组:

File file = new File("test.txt");

InputStream input = new FileInputStream(file);

byte[] byt = new byte[input.available()];

input.read(byt);

 

2、将byte数组转换为InputStream:

byte[] byt = new byte[1024];

InputStream input = new ByteArrayInputStream(byt);

 

3、将byte数组转换为File:

File file = new File('');

OutputStream output = new FileOutputStream(file);

BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);

bufferedOutput.write(byt);

 

4、byte数组写出到outputstream输出流

 byte[] file = clientFile.getFile();
outputStream=new BufferedOutputStream(response.getOutputStream());
int off=0;
int fileLength=file.length;
int count=fileLength/1024 +1;
int lastLength=1024;
for(int i=0;i<count;i++){
if(i==count-1){
lastLength= fileLength-off;
}
outputStream.write(file,off,lastLength);
off=off+1024;
}
//将字节数组的数据全部写入到输出流中
outputStream.flush();

posted @ 2017-01-10 13:34  HalleyZ  阅读(103505)  评论(0编辑  收藏  举报