有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何下载带socket的图像

所以我在做一个练习,使用socket从网络上获取图像。我不确定在存储图像字节然后创建文件时使用哪个类。到目前为止,我的代码是:

    import java.io.*;
    import java.net.*;
    import java.awt.image.*;
    import javax.imageio.stream.ImageInputStream;
    import javax.imageio.ImageIO;

    class MyClass{
        public static void main(String[] args)throws IOException{
            Socket s = new Socket();
            ImageInputStream s_in = null; //I'm not sure about this
            PrintWriter s_out = null;

            try{
                s.connect(new InetSocketAddress("data.pr4e.org",80));
                System.out.println("Connected");

                s_out = new PrintWriter(s.getOutputStream(), true);

                s_in = ImageIO.createImageInputStream(s.getInputStream());//nor this
            }
            catch (UnknownHostException e){
                System.err.println("Don't know about host");
                System.exit(1);
            }

            //Message to server
            String message = "GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n";
            s_out.println(message);

            //This is where it gets confusing
            OutputStream out = null;
            while (true){
            try{
            out = new BufferedOutputStream(new 
            FileOutputStream("C:\\Users\\Steff\\Desktop\\Java ejemplos\\cover3.jpg"));
            out.write(s_in.read());
            }
            finally{
              if(out != null){
              out.close();
           }  
        }
    }
}

}


共 (0) 个答案