try{
    src_image = http://location/temp/mapimage/img_1157433357280.gif
    URL url = new URL(src_image);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream is = connection.getInputStream();
    int length = connection.getContentLength();
    System.out.println(url.toString());
    FileOutputStream fos = new FileOutputStream("d:\\test.gif");
    byte b[] = new byte[length];
    while(true){
int i = is.read(b);
System.out.println(i);
if( i==-1 ) break;
fos.write(b);
    }
    fos.close();
}catch(Execption e){
}
现在的问题是有时候输出的图片是对的,有时候输出的图片下边就是一条条的乱码,我想问问什么原因,怎么解决。

解决方案 »

  1.   

    一个图片,因为这个图片是个绝对路径的图片,所以直接写地址就行了,图片没有问题,在IE里可以直接访问到,那不用inputStream流,你说的哈西流和序列化怎么做?再包装一下?
      

  2.   

    int length = connection.getContentLength();
        byte b[] = new byte[length];
        while(true){
    int i = is.read(b);
    if( i==-1 ) break;
    fos.write(b);
        }问题出在上面这几行代码。首先,没有必要根据 content length 开辟一个数组(如果图片文件很大的话,你岂不是很亏?),开一个固定大小的就可以了。其次,不应该等 read() 返回 -1 才结束,应该是读够了预期的字节数就结束,因为 -1 是要在对方关闭了 socket 时才会发生,你可能要为此多等待几秒钟(无谓的等待)。但是上面这两点都不是导致图片混乱的原因。真正的原因在于,你应该用 fos.write(b, 0, i),这才是真正从 input stream 里读出来的数据,而不包含空白的缓冲区。
      

  3.   

    while(true){
    int i = is.read(b);
    System.out.println(i);
    if( i==-1 ) break;
    // fos.write(b,0,i);
    } for(int i=0;i<b.length;i++){
    fos.write(b[i]);
    }
    如果我不想在while里输出呢?该怎么写,这么写肯定是不行的。
    给看看该怎么改造.
      

  4.   

    int length = connection.getContentLength();
    byte[] b = new byte[length];
    int ptr = 0;
    while(ptr < length){
        int i = is.read(b, ptr, length-ptr);
        if ( i == -1 ) break;
        ptr += i;
    }
    fos.write(b);不过我不明白,为什么你不想在 while 里输出呢?
      

  5.   

    再问个题外话,把这个byte[]数组放到blob字段里,再拿出来显示不会出问题吧.