Read a property file !

Hi all,
i have to read a property file; i put it under the directory WEB-INF/classes so i can read it using the classloader.
This works fine under Tomcat, but when i put my webapplication under SunONE, i must put this file under the directory /server1/config.......how cai force the system to read the file from the WEB-INF/classes directory without specifing an absolute path ?
Cheers.
Stefano

There are a couple of ways, but you need the ServletContext object.
ServletContext.getRealPath("websitePath")
ServletContext.getResourceAsStream("websitePath")
The first method converts a website relative path to a location on disk - eg /config -> c:\tomcat\webapps\myApp\config
The second actually opens a file at that location, and returns an input stream to it.
The second can be more portable, because if the container you are using does not "explode" the WAR file, the path returned refers to the target within the WAR file - and the java.io functions don't handle that case.
Cheers,
evnafets

Similar Messages

  • In Vista,  Applet isn�t able to read the property files

    I�m working on internationalization; the Applet which I�m using wasn�t able to read the property files properly in windows Vista machine. But if I create a jar which contains all the classes and property files, Applet works fine.
    This problem is only in Vista machine ,In XP the JVM is smart enough to read plain .property files and its works well without creating the jar
    Is that related to any security enhancemence of vista over XP?
    Below is a link about The Java Security Model break on Windows Vista
    http://bugs.sun.com/view_bug.do?bug_id=6548078
    I tried a simple ResourceBundle.getBundle() in my Applet in different ways but nothing work fine for me. It isn�t an issue related to path, I guess because I tried several ways like.
    ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle");
    ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle",currentLocale);
    ResourceBundle labels = ResourceBundle.getBundle("com.test.LabelsBundle");
    ResourceBundle labels = ResourceBundle.getBundle("com.test.LabelsBundle",currentLocale);The exception got in java console is
    CONFIG: [2008-05-13 15:54:57.909]:(com.satm.insite.InsiteApplet$2@1696e4c):InisiteApplet: Exception:  java.util.MissingResourceException: Can't find bundle for base name LabelsBundle, locale en
    java.util.MissingResourceException: Can't find bundle for base name LabelsBundle, locale en
                at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
                at java.util.ResourceBundle.getBundleImpl(Unknown Source)
                at java.util.ResourceBundle.getBundle(Unknown Source)
                at com.satm.insite.InsiteApplet.displayValue(InsiteApplet.java:261)
                at com.satm.insite.InsiteApplet.callme(InsiteApplet.java:296)
                at com.satm.insite.InsiteApplet.initialize(InsiteApplet.java:327)
                at com.satm.insite.InsiteApplet$2.run(InsiteApplet.java:235)
                at com.satm.tools.languageTools.ThreadPool$ExceptionCatchingThread.run(ThreadPool.java:226)Is there any way to make it work in Windows Vista machine�? This could be a great help for me.
    Thanks
    Robert

    Crossposted:
    http://forum.java.sun.com/thread.jspa?threadID=5295743&messageID=10250558#10250558
    http://forum.java.sun.com/thread.jspa?threadID=5295742&messageID=10250556#10250556

  • Error while reading a property file from a war.

    Hi,
    I am trying to read a property file which is available in the properties folder.
    The piece of code that does this read is as follows.
    InputStream is = ClassLoader.getSystemResourceAsStream("codemap.properties");
    System.out.println("Reading file:"+is);
    properties.load(is);
    The "codemap.properties" file is available in the properties folder.
    Following is my directory structure in the war file
    sample.war
    |
    |
    WEB-INF
    |
    |
    classes
    |
    |
    properties
    |
    |______ codemap.properties
    Inside the war file I have WEB-INF and properties folder.
    Inside WEB-INF i have the classes folder which has the classes
    Inside the properties folder I have the codemap.properties file.
    I am using Jboss. In the class path I have ./properties
    I have also added this classpath in the manifest file.
    Problem: The piece of code that I have written to read the property file is not able to locate the file and this it returns null.
    I am not sure what i am missing here.
    If anyone there have any solutions please let me know.
    Thanks in Advance
    Balaji.

    I think you've to change this line
    InputStream is = ClassLoader.getSystemResourceAsStream("codemap.properties");with this.
    InputStream is = ClassLoader.getSystemResourceAsStream("properties/codemap.properties");it is unable to find the path you specified. by default it'll check the WEB-INF directory. so you've to give the relative path to it.
    Diablo

  • Read a property file and store it in a hashmap

    Hi,
    I have tried to read a property file and store it in a hashmap. The property-names should be stored in keys and the property-values (after = symbol) in values of the hashmap. any ideas? Is it possible to do this?

    mandy2001ir wrote:
    yes, but I need the hashmap for another reason. Actually I'm trying to use the properties file to have a dynamic hachmap. I don't want to change the code anytime I want to put a value in the hashmap. therefor I write the "keys" and "values" in a property file and change the property file. That's the reasn why we have property files, isn't it?What's a "dynamic hashmap"? There's no other kind! Whenever someone starts bandying around the word "dynamic" in contexts like this, it usually means there's a simple solution to their problem, that they haven't yet considered, or mistakenly don't believe is applicable to them, because of this "unique" need for something "dynamic". Trust me, you just need to load the file using a Properties object, and you're done. Properties extends Hashtable, which is virtually the same thing as a HashMap. Properties does exactly what you want it to. it's the very reason the class exists
    Have you even looked at the javadoc for java.util.Properties yet? I'm betting not, because if you had, you'd know exactly what I meant. And since you haven't, I'm at a bit of a loss as to how you can so easily dismiss the class as useless, despite existing to do exactly what you need

  • How to read a property file..urgent

    Hi ,
    This is kinda urgent if you can help! I am a new bee to servlet and java.
    My JSP calls a java class file. In the class file i establish my connection to database.
    My requirement is to read a property file for the database name, username and password and connet to the database using JDBC(database is oracle).
    which class to use. I know something about properties class. Is there any other class which can read my property file.
    Or is there any other all together a better way to do it.
    thanks in advance
    Amit

    Inside your WAR file somewhere under the WEB-INF directory. This space is protected, whereas the ROOT (of course) is not. Unless you would like someone else to read your properties file...
    Once you decide where you want it, post the section of code where you load the properties file, we can probably help you figure out where you path is wrong.

  • How will read the property file on dynamically?

    hi,
    I developed 2 java files...in both the files i am reading the some content from .property file(Notes.properties)....
    I created the jar file call Aix.jar using the following command.
    jar -cvf Aix.jar *.class(without specifying the notes.properties file)...
    then i executed the java file using the folowing command
    java -cp Notes.jar;Aix.jar NotesToolTest
    now i am getting following exception:
    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.util.MissingResourceException: Can't find bundle for base name Notes, locale en_US
    at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
    at java.util.ResourceBundle.getBundleImpl(Unknown Source)
    at java.util.ResourceBundle.getBundle(Unknown Source)
    at NotesToolTest.<clinit>(NotesToolTest.java:28)
    I got the problem why this happening...because notes.properties is not included in jar file...that's why the above exception is coming.
    But my problem is can i run the java file that will take .prooperties file dynamically(if .property is available on the current directory)...
    Thanks in advance,,,,
    Regards,
    Sankar

    because notes.properties is not included in jar file..Wrong. It is simply not available in the classpath.
    The solution is either putting the properties file in the classpath of JVM used, or adding the system path to the propertiesfile to the classpath of the JAR.

  • Problem reading custom property file from custom event handler.

    Hi,
    My custom event handler needs some bits of information that I have set up in a property file. However, when the event handler runs it throws a FileNotFound exception - actually its because permission was denied.
    I have added the code System.getProperty("user.name") to find out the actual user that the event handler is running as. It reports that "oracle" is the user.
    That's great. However, the permissions on the file will allow oracle to read/write the file. If I log onto the server where OCDB runs (as oracle), I can vi the file.
    The file is owned by another user, but the "oracle" is a member of the group that has read/write (we're running on a unix box). The file is not 777.
    The event handler is actually calling a static utility method that returns the Properties. This utility is used elsewhere in other custom apps in conjunction with OCDB (on the same server). It works there, so the utility is functioning correctly.
    Is there something going on that I'm missing? Like somehow the event handler is acually runn as somebody else?
    Here is the node log.
    2007/07/17 12:52:16 [oracle.ifs] [37] 434364 system FINE: Error /opt/csc/sfi/configuration/sfi.properties (Permission
    denied) Additional INFO: java.io.FileNotFoundException: /opt/csc/sfi/configuration/sfi.properties (Permission denied)
    Thanks in advance for the help.
    Winston

    Matt,
    Sorry to have wasted your time. It was a server reboot issue. The ocdb server hasn't been restarted since early July. We added the users and groups late last week. Although we tested on line, the server wasn't quite up to speed with the new changes.
    We bounced the server and all is well.
    Thanks
    Winston

  • Read a property file value and display in jsp page

    I need a solution for the below mentioned scenario,
    I want to read a value from the property file in JSP page.
    For Example, Let us have a property file called A.properties, in the file, we have a value, username = Sam.
    I want to bring this value in the jsp page.
    Please assist in this issue.
    thanks in advance.

    If you are using struts, then you have to first load the taglib like
    <%@ taglib uri="/WEB-INF/strutsresources/struts-bean.tld" prefix="bean" %>and then access the particular property like
    <bean:message key="welcome"/>Also, you have to define <message-resources> in struts-config. Though I am not into struts for year now, So, please confirm the code.

  • Strategy to read a property file

              Hi all
              I'd like to know what could a good strategy with property files,where should I
              put them? Is it a good idea to put it in the war file? If so then how to read
              it from a jsp ?
              Thanks a lot
              Francesco
              

    Or you can put them in your /WEB-INF/classes directory and read them
              this.getClass().getResourceAsStream("/yourp.properties");
              Note that you need to put the / before the name (refer to the
              java.lang.Class documentation)
              Or if you have an ear application do:
              put your properties files in directory that you place in the ear file:
              /propertiesDir/myprop.properties
              in the manifest file of your war put a Class-Path = propertiesDir
              entry
              again do:
              this.getClass().getResourceAsStream("/myprop.properties");
              Simone
              Dimitri Rakitine <[email protected]> wrote in message news:<[email protected]>...
              > You can put it in a war (say, in /WEB-INF/) and use
              > application.getResourceAsStream("/WEB-INF/your.properties")
              > to read it
              >
              > Francesco <[email protected]> wrote:
              >
              > > Hi all
              > > I'd like to know what could a good strategy with property files,where should I
              > > put them? Is it a good idea to put it in the war file? If so then how to read
              > > it from a jsp ?
              > > Thanks a lot
              > > Francesco
              

  • Error Reading Property File in Portal Component

    Hello,
    I have created a portal component that calls an api that is located in a jar file.  The documentation on the Portal Component Structure specifies putting the jar file in the PORTAL-INF/lib directory, which I have done.  The problem is, my jar file reads a property file using ResourceBundle, but it doesn't find the property file.  I have placed the property file in the jar file, and throughout the portal component structure, but it just can't find it.  Has anyone else done something similar?  If so, where did you put your property file(s) for external jars that are used in the portal component.
    EP6 SP2 Patch27
    thanks,
    Keith

    Hi,
    I had similar issues and moved the property files to PORTAL-INF/classes.
    Best Regards
    Frank

  • Read from a property file which is in a zip

    I have the problem, that I can�t read a property file in a zip. A class which I ca get in the same zip needs this property to init.
    I call this in a batchfile.
    The message is like:
    c:/xx/core.zip!/com/xx/Prop.properties
    Path of the zip Path of the Property in zip
    Syntax or name or path are not correct.
    Where is the problem?
    Thanks in advance
    Frank

    hm, am not sure I follow but
    it is not possible to instantiate the class. I only use this class. >Java will find the class in the same zip and path, but the property->File will not be loaded while a FileInputStream wonts to open it.FileInputStream can't be used to open a zipped file, you can get an InputStream from the ressources variable by using URL.openStream method and feed this into Properties.load
    if you post some code here that you are able to change, then people might be able to help more :)
    asjf

  • Where is the correct place to put a property file to be read by bpel ?

    Hi.
    I need to create a custom property file and configure SOA Suite to load it as it's own resource during its start. So i can read this property file from my BPEL embedded activity with some code like this:
    Properties prop = new Properties();
    InputStream in = getClass().getResourceAsStream("foo.properties");
    prop.load(in);
    in.close()
    Avoiding the use of the FileInputStream (constant IO, fixed paths..).
    Is there some default place to put this file ? I have tried to put it under applib and configure this directory as a shared-library directory but without success.
    I'm using SOA Suite 10.1.3.5 with OC4J.
    Thanks.

    Properties can also be defined in and read from bpel.xml. you can define token with any name and define the value for it. In your configuration you can use tokens and at run time it will read the values from bpel.xml.
    Thanks,
    Vikas Manchanda

  • FILENOTFOUNDEXCEPTION while reading property files in Tomcat 6------Help me

    Hi All
    I am planning to migrate my web application from iplanet 4.1 to tomcat 6. In this process I need to read the properties files initially.
    for eg: i got the property files in a iPlanet:
    Config directory---
    abc.properties.---
    abc.log--
    In tomcat I configured them in web.xml saying that.
    <servlet>
    <servlet-name>ABC</servlet-name>
    <servlet-class>com.ijk.abc</servlet-class>
    <init-param>
    <param-name>Loan</param-name>
    <param-value>/WEB-INF/config</param-value>
    </init-param>
    <init-param>
    <param-name>loan.props</param-name>
    <param-value>/WEB-INF/config/abc.props</param-value>
    </init-param>
    <init-param>
    <param-name>loan.log</param-name>
    <param-value>/WEB-INF/config/abc.log</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>ABC</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    I need to read initially all the property files and then proceed.
    While configuring in this way, it am getting error saying that
    abc.props or abc.log..............(FILE NOT FOUND EXCEPTION)
    Can anyone suggest me how to configure them.
    Thanks in Advance.

    Thanks for your response, Actually we dont have the source code for that because it is very old code, but i m using decompiler in which i can get some informtaion.
    OS used for iPlanet is Unix but now I need to deploy this application in tomcat in windows server 2003.
    Servlet clss:
    SERVLET CLASS:
    Class com.ijk.abc implements extends HttpServlet  implements PropertyKeys
    private IClickManager m_im;
    public void init(ServletConfig paramServletConfig)
        throws ServletException
        Utils.info("Servlet initialization");
        try {
          super.init(paramServletConfig);
          Utils.info("ServerInfo: " + getServletContext().getServerInfo());
          PGroup localPGroup = this.m_im.claimPG();
          Utils.trace("Got " + localProcessorGroup + " for initialization");
          this.m_im.gatherProperties(localProcessorGroup);-----------this is where it is calling the property files.
          this.m_im.freePG(localPGroup);
          Utils.trace("Released " + localPGroup + " for new Properties");
          localPGroup = this.m_im.claimPG();
          Utils.trace("Got " + localPGroup + " for new Properties");
          try
            ConHandler localDBHandler = (ConHandler)localPGroup.getDBHandler("config.dbhandler");
            this.m_im.setNumPGs(localDBHandler.getNumPGroups());
          catch (Exception localException1) {
            Utils.info("NON FATAL ERROR: failed to set number of PGs", localException1);
          try
            Session.createAndStartSessionTask(localPGroup);
            localPGroup.resumeAllTasks();
          catch (Exception localException2) {
            Utils.info("NON FATAL ERROR: failed to start tasks", localException2);
          this.m_im.freePG(localPGroup);
          Utils.trace("Released " + localPGroup + " for initialization");
          Utils.info("Servlet initialization finished");
        catch (FatalServletError localFatalServletError) {
          Utils.error("FatalServletError: ", localFatalServletError);
          throw new UnavailableException(this, localFatalServletError.toString());
        catch (Error localError) {
          Utils.error("Error: ", localError);
          throw localError;
    ==========================================================
    public void gatherProperties(ProcessorGroup paramProcessorGroup)
        Object localObject;
        this.m_props.clear();
        String str1 = this.m_servlet.getInitParameter("loan.dir");
        if (str1 == null) {
          str1 = System.getProperty("server.root", System.getProperty("user.dir", "."));
        this.m_props.put("loan.dir", str1);
        String str2 = this.m_servlet.getInitParameter("abc.log");
        setLogFile(str2);
        try
          String str3 = this.m_servlet.getInitParameter("abc.props");
          if (str3 == null)
            str3 = "abc.props";
          localObject = str1 + File.separator + str3;
          Utils.info("Reading properties from file: " + ((String)localObject));
          Utils.loadProperties(this.m_props, new BufferedInputStream(new FileInputStream((String)localObject)));
        catch (IOException localIOException) {
          Utils.info("NON FATAL WARNING: Could not read props file", localIOException);--while running i m getting this error
        Utils.info("Reading properties from Servlet Parameters");
        Enumeration localEnumeration = this.m_servlet.getInitParameterNames();
        while (localEnumeration.hasMoreElements()) {
          localObject = (String)localEnumeration.nextElement();
          this.m_props.put(localObject, this.m_servlet.getInitParameter((String)localObject));
        Utils.info("Reading properties from DB");
        try {
          localObject = (ConDBHandler)paramProcessorGroup.getDBHandler("config.dbhandler");
          String str5 = ((ConDBHandler)localObject).getPropertiesFile();
          Utils.loadProperties(this.m_props, new ByteArrayInputStream(str5.getBytes()));
        catch (Exception localException) {
          Utils.info("NON FATAL WARNING: Could not read props file", localIOException);--while running i m getting this error
        String str4 = this.m_props.getProperty("smtp.host");
        if (str4 != null) MailUtils.setSMTPHost(str4.trim());
        if (str2 == null) {
          str2 = this.m_props.getProperty("abc.log");
          setLogFile(str2);
         runInitializers(paramPGroup);
        Utils.info("New Properties:", this.m_props);
        this.m_rroots = StringUtils.getPathsFromList(this.m_props.getProperty("resource.path", "/com/loan/resources/:/"));
        clearAllPGs();
    =================================================================
    the above is the servlet class and the method which is using to read the property files from root directory in Unix.
    ie../opt/mywebapp/loan/abc.props,abc.log
    loan is the directory in which two property files are placed.
    i just want to where to place property files in tomcat so that its going to read the property files.
    Right now, i placing it in the WEBAPPS/MYWEBAPPLICATION/WEB-INF/LOAN/abc.props,abc.logs.
    Its giving me errors such as FILENOTFOUNDEXCEPTION or cannot read the property files.
    The main problem is ...I donot have the complete source code. while decompiling i m not able view complete source code.
    Please help me regarding this.........
    Thanks in advance.

  • Maven Plugin not accepting values from a property file.

    Hi,
    I want to create javadocs using maven.
    It works fine when i provide all the absolute paths in the pom.
    But when i try to provide paths by reading a property file then the maven-javadoc-plugin does not get the paths from this property file.
    The property file is defined as mentioned in below format:
    src_mvn_consult_framework_dir=/var/lib/hudson/jobs/CZ_NAB_CORE_MVN_CHECKOUT/workspace/middleware/projects/framework
    src_mvn_consult_module_dir=/var/lib/hudson/jobs/CZ_NAB_CORE_MVN_CHECKOUT/workspace/middleware/projects/module
    src_mvn_consult_appx_dir=/var/lib/hudson/jobs/CZ_NAB_CORE_MVN_CHECKOUT/workspace/middleware/projects/appx
    src_mvn_consult_client_dir=/var/lib/hudson/jobs/CZ_NAB_CORE_MVN_CHECKOUT/workspace/middleware/projects/client
    src_mvn_consult_app_webservice_dir=/var/lib/hudson/jobs/CZ_NAB_CORE_MVN_CHECKOUT/workspace/middleware/application/com.ofss.fc.cz.nab.webservices
    src_mvn_consult_app_middleware_dir=/var/lib/hudson/jobs/CZ_NAB_CORE_MVN_CHECKOUT/workspace/middleware/application/com.ofss.fc.cz.nab.middleware
    Calling this property file in the pom like:
    <plugin>
         <groupId>org.codehaus.mojo</groupId>
         <artifactId>properties-maven-plugin</artifactId>
         <version>1.0-alpha-2</version>
         <executions>
         <execution>
         <phase>initialize</phase>
         <goals>
    <goal>read-project-properties</goal>
         </goals>
         <configuration>
    <files>
         <file>/var/build/consult/maven/cz_javadoc-config.properties</file>
    </files>
         </configuration>
         </execution>
         </executions>
    </plugin>
    Finally we are using keys defined in property file in pom like:
    <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
              <version>2.7</version>
              <configuration>
              <sourcepath>${src_mvn_consult_framework_dir};
                   ${src_mvn_consult_module_dir};
                   ${src_mvn_consult_appx_dir};
                   ${src_mvn_consult_client_dir};
                   ${src_mvn_consult_app_webservice_dir};
                   ${src_mvn_consult_app_middleware_dir};
              </sourcepath>
              </configuration>
    </plugin>
    Please suggest how we can get the value of keys defined in the property file in POM
    Thanks for your invaluable support

    I've had to do something similar in one of my apps.  In order to populate values in the THIS scope, you'll need to put a copy of the XML loading/processing logic in the pseudo-constructor (or encapsulate it in a separate CFM/CFC file and include it in both places).  It's ugly, but that's the only way I'm aware of to access the THIS scope.
    -Carl V.

  • How to Read a CAB File from JAVA?

    Hi,
    Anyone knows how to read a CAB File from java. I need to read a property file of txt file that is packaged in CAB file & then based on that, I have to do processing. Is there anyway to do it.
    I had tried using java.util.zip.ZipFile Class, but it does work for JAR, but not for CAB.
    siva.

    Perhaps there's something in the Cabinet SDK that will help:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncabsdk/html/cabdl.asp

Maybe you are looking for

  • I am trying to manage my website, why can't I cut and paste information or even url?

    I have only had this imac for 24 hours, it doesnt seem to have basic functions like cut and past even using the commands control c and V.  I run 2 websites and its completely frustrating, can anyone help please... otherwise its going back...

  • Can I embed fonts of all Dynamic Text objects in a Flash file?

    Hi there! I'm fairly new to Flash, so please bear with me. I have created a Flash file which will act as our company's standard presentation / portfolio of all previous projects.  I've pretty much got it running the way I want, but I've just tried it

  • Access to Safari is blocked because Apple file is allegedly damaged

    An alert from <techsupportnumber.us> appears repeatedly when I try to use Safari on my MacBook Pro (OSX Lion). It says that my Apple file has been damaged and that I should contact Apple customer care. The phone number is different from the Apple sup

  • Why does Finder only burn DVD's at 2x?

    I have a MacBook Pro with a 8x Superdrive. How come when I try to burn a data dump onto DVD from the finder, the only option I have is 2x? I can't even go lower to 1x let alone the advertised speed of 4x. here are the specs of the drive: Maximum writ

  • External table in Oracle 10g and Windows server 2003

    I'm having a problem accessing an external table in an Oracle 10g and Windows 2003 server environment. The disk is remote (mapped) to the server. It's the usual access errors, kup-04001 or kup-04063. I have the [seemingly] exact same setup in an Orac