FileOutPutStream写文件,这个大家应该很熟悉了,当接收的是一个InputStream文件时,一个一直困扰我的问题是,在定义写文件时每次写入的大小,也就是byte[] 数组大小的定义。
经过网上查找,学会了一招,记录一下:
public static void writeLocal(InputStream instream) {
File file = new File("C:/result.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while(true) {
if(instream.available() < 1024) { // 剩余的数据比1024字节少,一位一位读出再写入目的文件
int c = -1;
while((c = instream.read()) != -1) {
fos.write(c);
}
break;
}
else {
// 从来源文件读取数据至缓冲区
instream.read(buffer);
// 将数组数据写入目的文件
fos.write(buffer);
}
}
instream.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}