使用场景: 之前用HttpClient做了一个文件下载模块,但是请求来的数据是流形式,因此需要将流还原成文件,于是用到以下方法;
原理: 本方法原理是先用固定字节数读取输入流,再将其写入文件输出流,先读后写完成流到文件的转换,顺便研究了下arraycopy()
的用法;
代码: 输入流转化成文件
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamToFile {
/**
* 流转换成文件
* @param inputStream
*/
public void inputStreamToFile(InputStream inputStream){
try{
//新建文件
File file = new File("D:/demo/demo.zip");
if (file.exists()){
file.createNewFile();
}
OutputStream os = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024 * 1024];
//先读后写
while ((read = inputStream.read(bytes)) > 0){
byte[] wBytes = new byte[read];
System.arraycopy(bytes, 0, wBytes, 0, read);
os.write(wBytes);
}
os.flush();
os.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
arraycopy() 方法
功能:将指定源数组从指定位置复制到目标数组的指定位置
参数:源数组(src
),源数组读出的位置(srcPos
),目标数组(dest
),目标数组写入的位置(destPos
),需要赋值数据的长度(length
)
用法:System.arraycopy()
*************************************源码********************************************
* Copies an array from the specified source array, beginning at the
* specified position, to the specified position of the destination array.
* @param src the source array. // 源数组
* @param srcPos starting position in the source array. // 源数组读出的位置
* @param dest the destination array. // 目标数组,往里写的
* @param destPos starting position in the destination data. // 目标数组写入的位置
* @param length the number of array elements to be copied. // 需要赋值数据的长度
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);