aspose file tools*
The moose likes I/O and Streams and the fly likes How to retrieve file contents using sockets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "How to retrieve file contents using sockets" Watch "How to retrieve file contents using sockets" New topic
Author

How to retrieve file contents using sockets

Avan Chua
Greenhorn

Joined: Sep 19, 2013
Posts: 2
Hi, I an new to java.

I am trying to retrieving a file content from a given server and file path.
The file could be a text, html or image file.

I tried reading the content as bytes but the image will not display:

The following is a segment of my code:

byte[] b = new byte[1024];

Socket socket = new Socket(hostname,80);

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
out.println("GET /" + file + " HTTP/1.1");
out.println("Host: " + hostname);
out.println();
out.flush();

DataInputStream reader = new DataInputStream(socket.getInputStream());

int i = 10;
File outputfile = new File(outFileName);
FileOutputStream outfile = new FileOutputStream(outputfile);

while ((i = reader.read(b)) != -1) {
outfile.write(b,0, i);
}

I was able to read the contents for text and html but not image file, I do not know why?!. In addition, my output file will contain the http response code which I want to omit but could not
as I am reading everything as bytes, I would not know the particular position the http response code ends to decide which to write and what item not to write.

Can anyone help with my 2 questions?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12806
    
    5
I was able to read the contents for text and html but not image file, I do not know why?!


For one reason - readers perform a character conversion on input bytes.

Furthermore, how are you handling the response headers? Wouldn't it be easier to use the standard library - java.net package HttpURLConnection class?

Bill

Avan Chua
Greenhorn

Joined: Sep 19, 2013
Posts: 2
How do I use it? the HttpURL Connection, is there any examples on how to use it that you could show me? I am really new to this.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18669
    
    8

Your web search keywords for that question would be: java HttpURLConnection example. I'm sure you should be able to find an example of that class online if you just search a bit.
 
 
subject: How to retrieve file contents using sockets