URLs are your friend
It's amazing how cool URLs are, especially when you think of them as more than just web references. If you use them instead of Files, you can end up with applications that are much more flexible. I've gotten to the point where I hardly use class File at all - I almost always use URLs. They can be really cool when you start exploiting synergies with other APIs.For example, drag-and-drop. This seems like an odd one to relate to URLs, but it does. Drag-and-drop can be somewhat erratic from one system to another. For example, on some systems when you drag from a file browser, you never see a file dropped on you, you just see a string that contains the name of the file. The same thing can happen with a web browser: dragging an image or a link sometimes drops a string, or a file. This isn't odd behavior in the D&D handling in the Java libraries, it's in the originating application. These days, when I write code that deals with strings being dropped on me, I will often try to interpret them as other types. For example, if new File(s).exists() is true, I convert the file to a URL with new File(s).toURL(). If it doesn't look like a file, then I try new URL(s).openStream(). If this succeeds, then I use that URL as the data source. In either case, the data source looks like a URL. This way I can drag from either a file browser or a web browser and it all works uniformly.
Another thing to try is to use URLClassLoader as a general repository manager, not as a class loader. Say you're doing something like a document editor or a presentation tool. The document often has associated resources, like images. If you reference the images using URLs, then they can reside anywhere: on the local file system, across the net, or packaged inside a zip file - that's where URLClassLoader comes it. A Jar file is just a zipped archive of a bunch of files. Applying getResource to a URLClassLoader attached to a zip file returns a URL that, when opened, get's you to the file bundled as a component of the zip file. So you represent a document as a zip file that contains the document data itself, and all the associated external data objects (like image files) that you want to bundle with it.
August 22, 2003 |