Using URL class to access files in local system as well as on web

I’ve being trying to do this for a while and I accidentally stumbled upon the solution. Until then I was using the “File” class whenever I wanted to access a local file and “URL” class whenever I want to access some thing on the web, and treat each case separately.

So If I wanted to treat the both cases in the same way the answer is to use the “URL” class. There are some drawbacks on using this class, but when the occasion presents it self best to use this class. The trick is that URL class expects the address specified has the protocol included in it when an object of it is instantiated.

For example for a web address you always have to specify the address for the URL class starting with the protocol such as “” . Similarly If you want to access a file in the local file system just use the absolute path with the protocol “file://” as the suffix. (eg: “file:///home/saminda/Desktop/myfile.xml”)

eg : URL url=new URL("file:///home/saminda/Desktop/myfile.xml")

Or you can just use the other available constructors to specify the protocol seperately. Check the URL api here. There are many other protocols supported by URL class. They are,

  • file
  • ftp
  • gopher
  • http
  • mailto
  • appletresource
  • doc
  • netdoc
  • systemresource
  • verbatim

Exact implementations of supported protocols can vary. Above set is from sun java.


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: