So I'm doing the exercise of getting an image from the web using Sockets. I'm not sure which class to use when storing bytes of an image to then create the file. My code so far is:
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();
}
}
}
}
}