'URL'에 해당되는 글 1건

  1. 2010.01.19 Using java.net.URL for input stream access 8
2010. 1. 19. 18:04

Using java.net.URL for input stream access





I was talking with Andrew Wills the other day about the java.io.File class. We were debating the merits of java.io.File versus just using a String to track the filename instead. Upon further reflection, it seemed that being able to open a stream from the object that was being carried around, would be useful, and this was something neither java.io.File nor String could do. I suggested possibly looking at java.net.URL.

After we talked a little more about how java.net.URL captures both the identity and ability to open a stream needs he had, we thought about the other benefits java.net.URL might have. I suggested it could also be used for different protocols beyond just web and local files. For example FTP files might now be available for retrieval. Thinking a little more about this, I started to second guess myself. I was pretty sure FTP required more interactive work then HTTP and FILE based URLs.

So, like any good developer I went back to my desk and began the Google search ritual. You know the drill, come up with a few keywords, and hit the search button. Then based on the results, you come up with new ways to word your search criteria, and you search again. After enough searching you sometimes come up with something useful. This was my case, I finally found a forum thread somewhere about a person having difficulty with an FTP URL. In their case, the filename had spaces in it, and it was a problem of escaping the spaces too many times. But out of that post I found the core code to use an FTP resource was not really much different from other java.net.URL work I've done. Matter of fact it looked pretty much the same. So, I created this program to test my theory out.

import java.net.*;
import java.io.*;

public class URLReader {

	public static void main(String[] args) throws Exception {
		URL url = new URL(args[0]);
		URLConnection uc = url.openConnection();

		InputStreamReader input = new InputStreamReader(uc.getInputStream());
		BufferedReader in = new BufferedReader(input);
		String inputLine;

		while ((inputLine = in.readLine()) != null) {
			System.out.println(inputLine);
		}

		in.close();
	}
}

You can then run the above code like this:

As you can see, the same code will work with three different protocol based URLs. This can be useful when you're looking for code that is flexible in obtaining the data it needs.

---- Cris J H