Java通过Http请求下载文本附件到本地

 
//首先通过socket获取下载流
InputStream is=socket.getInputStream();
int lengt = 1024;//根据实际情况获得
final ByteArrayOutputStream baos = readLengthData(is,length);//读取未经解压的数据流
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
GZIPInputStream in = new GZIPInputStream(bais);//将未解压的数据流放入GZIP流进行解压
final BufferedInputStream bis = new BufferedInputStream(is);//输出解压后的字符流
final ByteArrayOutputStream newbaos = new ByteArrayOutputStream();

while(bis.available() > 0) {
   newbaos.write(bis.read());//转换为字节
}
byte[] content = newbaos.toByteArray();
FileOutputStream outf= new FileOutputStream(file,append);
        	
//          ObjectOutputStream oos = new ObjectOutputStream(outf);//用objectouput可能会在文件头多写几个字节码
//          oos.write(content);
//          oos.close();
            
  BufferedOutputStream bufferout= new BufferedOutputStream(outf);
  bufferout.write(content);
  bufferout.flush();
  bufferout.close();
 
 

private final ByteArrayOutputStream readLengthData(final InputStream is, final int length) throws IOException {

  final BufferedInputStream bis = new BufferedInputStream(is);   final ByteArrayOutputStream baos = new ByteArrayOutputStream();

  int read = 0;   int total = length;   while(read < total) {    total -= read;    byte[] result = new byte[total];    read = bis.read(result);    baos.write(result, 0, read);   }   while(bis.available() > 0) {

int num = bis.read();    if(num == 255 || num == -1){     continue;    }    baos.write(bis.read());   }   return baos;  }


你可能感兴趣的:(java,socket,File,byte)