🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #14615

Re: Absolute path to class file

#14615
From: kimptoc
Date: Thu, 19 Aug 1999 00:00
57 lines
2419 bytes
In article <934885178.20129.0.nnrp-14.c3add604@news.demon.co.uk>,
  "Ben Starr" <BenS@compurp.org.uk> wrote:
> Is there a way to find out the absolute path of the .class file a
Class was
> loaded from? I want a class to reference a text file on the disk
stored in
> the same directory as its .class file without having to hard-code the
path.

I don't know of any - but if you use the classloader.getResource, you
can access files (data or image etc) on the classpath.

Here's 2 methods;

   public static Reader getFile(String filenameIn)
   {
      URL url = getResource(filenameIn);
      if (url != null)
      {
         try {
            return new InputStreamReader(url.openStream());
         } catch (IOException err)
         {
            err.printStackTrace();
         }
      }
      return null;
   }

   private static URL getResource(String resource)
   {
      URL url = null;
      ClassLoader clr = ImageHelper.class.getClassLoader();
      if (clr == null)
      {
         //no current class, class loader - so use system one
         url = ClassLoader.getSystemResource(resource);
      } else
      {//use current class's class loader
         url = clr.getResource(resource);
      }
      return url;
   }

This works for files located with the class files, or in the same jar
file - even if loaded via an applet.

The filenameIn need to specify the full path, using url type naming -
eg your class is in package com.abc.pkge. The data file is in the same
directory, then filenameIn should be "com/abc/pkge/data.file"

Hope this helps,
Chris


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
Technical Details
Message-ID: <7pgs5d$nik$1@nnrp1.deja.com>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <934885178.20129.0.nnrp-14.c3add604@news.demon.co.uk>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,488dd600984f352c
X-Google-Attributes: gidf74b3,public
From: kimptoc@my-deja.com
Subject: Re: Absolute path to class file
Date: 1999/08/19
Message-ID: <7pgs5d$nik$1@nnrp1.deja.com>
X-Deja-AN: 514637660
References: <934885178.20129.0.nnrp-14.c3add604@news.demon.co.uk>
X-Http-Proxy: 1.0 x42.deja.com:80 (Squid/1.1.22) for client 194.131.192.215
Organization: Deja.com - Share what you know. Learn what you don't.
X-Article-Creation-Date: Thu Aug 19 12:09:24 1999 GMT
X-MyDeja-Info: XMYDJUIDkimptoc
Newsgroups: borland.public.jbuilder.java.language
X-Http-User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DIL0001009; DigExt)