Question

I have a piece of code that retrieves a file either from a remote server or from the local disk.

I understand that URLConnection can handle both cases, so I was wondering if there was any performance advantage if I used FileInputStream to read the local file rather than just handing it off to URLConnection to read from disk?

Was it helpful?

Solution

No, there's no performance advantage to using FileInputStream over a URLConnection (well, unless you're counting the milliseconds of a handful of extra method calls).

Reading a file via a file:// URL eventually gets you a FileURLConnection (note that this is not part of the official Java library spec, just the Sun-based JREs). If you look at the code, you'll see that it's creating a FileInputStream to work with the file on disk. So other than walking a few layers further down in the stack, the code ends up exactly the same.

The reason why you'd want to use a FileInputStream directly is for clarity of your code. Turning a file path into a URL is a little ugly, and it'd be confusing to do it if you were only ever going to work with files.

In your case, where you need to work with URLs some of the time, it's quite convenient that you can use a file URL and only work with URLs. I imagine you've abstracted nearly all of the interesting logic to work on URLs and can do the ugly business of constructing a file or non-file URL elsewhere.

OTHER TIPS

A FileInputStream obtains input bytes from a file in a file system. FileInputStream is meant for reading streams of raw bytes such as image data.

FileReader is meant for reading streams of characters.

In general, creating a connection to a URL is a multistep process:

  1. The connection object is created by invoking the openConnection method on a URL.
  2. The setup parameters and general request properties are manipulated.
  3. The actual connection to the remote object is made, using the connect method.
  4. The remote object becomes available. The header fields and the contents of the remote object can be accessed.

I think a good rule of thumb is to use the simplest code (object) possible in order to remain the most efficient. Think minimalist!

P.S. Not sure if you're just moving the file or reading its contents.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top