Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #35193
| From | Eric Sosman <esosman@comcast-dot-net.invalid> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: A little help with some logic |
| Date | 2016-08-04 09:28 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <nnvfu8$vov$1@dont-email.me> (permalink) |
| References | <nnugtj$78m$1@dont-email.me> |
On 8/4/2016 12:39 AM, Knute Johnson wrote:
> I don't know maybe it is too late but I can't seem to come up with
> anything better than this. What I need to do is take a String that
> contains the name of a file in my program's JAR file, a URL for a
> network site or the name of a file on the accessible file system and
> turn it into a URI. I want to check in that order, in the JAR file, a
> file on the filesystem or a network reachable URL. Even this has some
> holes and it is really ugly. Thanks...
>
> URI uri = null;
> URL url = getClass().getResource(fname);
> if (url == null) {
> try {
> url = new URL(fname);
> } catch (MalformedURLException murle) {
> uri = new File(fname).toURI();
> }
> }
> if (uri == null) {
> try {
> uri = url.toURI();
> } catch (URISyntaxException urise) {
> urise.printStackTrace();
> }
> }
>
> if (uri != null)
> // do something with the URI
(This checks in the first order you mention, so I guess the
second order was an "it is too late" slip-up.)
It seems clear enough to me. All I'd suggest is that an
exists() test might be a good idea in the File case, and that
something more severe than printStackTrace() is probably called
for if URISyntaxException gets thrown.
One other item that might or might not interest you: I've seen
that File's toURI() sometimes omits the "authority" part, giving
the unusable "file:/C:/foo.dat" instead of "file:///C:/foo.dat".
When I first ran into this I got around it with some heavy-handed
string-bashing, but (says the JavaDoc) the java.nio.Path{,s} classes
may offer a better way. Haven't tried them myself (for this purpose).
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
A little help with some logic Knute Johnson <nospam@rabbitbrush.frazmtn.com> - 2016-08-03 21:39 -0700
Re: A little help with some logic Eric Sosman <esosman@comcast-dot-net.invalid> - 2016-08-04 09:28 -0400
Re: A little help with some logic Knute Johnson <nospam@rabbitbrush.frazmtn.com> - 2016-08-04 16:44 -0700
Re: A little help with some logic Robert Klemme <shortcutter@googlemail.com> - 2016-08-06 11:13 +0200
csiph-web