2013-03-12 58 views
1
public class Socket { 
    public Socket() { 
     try { 
      URL url = new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg"); 
      InputStream in = url.openStream(); 
      BufferedInputStream bin = new BufferedInputStream(in); 


      ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); 
      byte[] okunan = new byte[4096]; 

      while(in.read()!= -1){ 
       bout.write(okunan, 0, in.read()); 

      } 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我得到这个错误:在java.io.ByteArrayOutputStream.write 异常线程 “main” java.lang.IndexOutOfBoundsException (来源不明)的Java读取JPG文件从URL

我想读这个jpeg文件在bytearrayoutputstream中写入文件之后。

索里我的英文不好..

回答

2

试试这个

BufferedImage img = ImageIO.read(new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg")); 
+0

感谢您的帮助所有的;) – kibar 2013-03-12 10:37:51

0

使用ImageIO API

BufferedImage img = ImageIO.read(new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg")); 

ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
ImageIO.write(img, "jpg", bout); 

检查thisthis的信息

0

你的意思是这样

try { 
     URL url = new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg"); 
     InputStream in = url.openStream(); 
     BufferedInputStream bin = new BufferedInputStream(in); 


     ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); 
     byte[] okunan = new byte[4096]; 

     while(in.read()!= -1){ 
      in.read(okunan); 
      bout.write(okunan); 

     } 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }