Is this how to use a properties file?

Hi:
The following is how I intend to create and read a properties file, please verify for me that the idea is correct.
1. create myProp.properties
2. in myProp, the content is like such:
a=myA
b=myB
c=myC
3. In my application,
  FileInputStream in = new FileInputStream(getClass().getResourceAsStream("/myProp.properties"));
  Properties p = new Properties();
  p.load(in);
  String a = p.getProperty("a");
  String b = p.getProperty("b");
  String c = p.getProperty("c");Thanx!

It depends on what youare doing but if you have a set of properties that you are going to always use from one running of the application to the next, they should generally be defined as static finals.
For example, lets say you want a configuration file for an application that holds the user's preferences. You might want something like this:
public class Preferences {
   private static final String ALWAYS_ON_TOP = "always on top";
   private Properities preferences = new Properties();
   static {
      //load the file
   public boolean setAlwaysOnTop(boolean alwaysOnTop) {
      preferences.put(ALWAYS_ON_TOP, String.valueOf(alwaysOnTop));
   public boolean getAlwaysOnTop() {
      return Boolean.valueOf(preferences.get(ALWAYS_ON_TOP));
   public void save() {
      /save file
}

Similar Messages

  • How to load Java properties file dynamically using weblogic server

    Hi,
    We are using Java properties file in Java code. Properties in java properties file are frequently modified. If I keep these properties file in project classpath or as part of war, I will have to redeploy application after each change.
    We are using Weblogic Server.
    Can you please suggest me how can this properties file be loaded at weblogic server startup. Then in that case, how to refer property file in Java code?
    What is the best practice for this?
    Thanks,
    Parshant

    Another alternative is, keep the property file in any pre-defined location. Write a class which reads the properties from the file and returns the one which is requested by caller and deploy this class. Whenever you have to change the properties just update the property file on server and next call to fetch the property should return the updated one.
    Downside of this approach is file I/O everytime. To overcome that you can actually "cache" the properties in a hashmap. Basically when any property if requested, first check the hashmap, if not found then only read from property file and also update in hash map. Next time same property will be returned from hash map itself. The hash map will be cleared at every server restart since its in the memory. You will also need to build a method to clear the hashmap when you update the values in the property file on server.
    This solution would be suitable for small size files and when network overhead of calling a DB needs to be avoided.

  • How we write into properties file using get class method

    Hi
    I want to set some value into properties file using given code
    can any one please tell me how i can do this.
    property file
    setting.properties
    Name     =     abc
    and code I use is
    java.io.InputStream oInputStream = this.getClass().getResourceAsStream("Setting.properties");
                   Properties obj = new Properties();
                   obj.load(oInputStream);
                   String myName = obj.getProperty("Name");
                   System.out.println("myName :"+myName);
                   obj.setProperty("Name","def");
                   FileOutputStream oOutput= new FileOutputStream("Setting.properties");
                   obj.store(oOutput, "");
    thanks.

    You can't.
    If you have properties that change dynamically, you should not be using a properties file that sits in the classpath, you should be using Preferences, or a properties file that sits in some application or possibly even user directory, but not one in the classpath. The proper way to do this, would be to have a properties file in your jar (or otherwise in your classpath) that contains the defaults, and another one outside of the classpath in one of the twwo above mentioned areas, then, you read the default one only if the other doesn't exist, or you read the default one first, then read the other overwriting the values from the defaults.
    Don't forget to save the properties again (right after loading if you loaded, or always load, the defaults) after every change.

  • How to use a key file in the FTP Task using and SSL connection

    In the past I have used this code to set the FTP pass word in an FTP component task in SSIS.
    Does anyone know how to use a Key file in an SSL connection to download a file from an FTP site?  If not can you tell me where I can get the C# code examples to learn how to create a script task or if there is another way in SSIS to download large files
    from an SSL FTP site?  Thank you for any help offered.
    public void Main()
    ConnectionManager FTPConn;
    FTPConn = Dts.Connections["FTPServer"];
    FTPConn.Properties["ServerPassword"].SetValue(FTPConn, Dts.Variables["FTPPassword"].Value);
    Dts.TaskResult = (int)ScriptResults.Success;
    Antonio

    You can use SFTP for this.
    This is a way of implementing SFTP in SSIS using standard tasks 
    http://visakhm.blogspot.in/2012/12/implementing-dynamic-secure-ftp-process.html
    also see
    http://blog.goanywheremft.com/2011/10/20/sftp-ftps-secure-ftp-transfers/
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Using Search_replace.properties file

    I am trying to use Migration assistant to migrate my forms form 6i to 10g.
    While doing so , I want to use search_replace.properties file to search for soem strings and automatically replace them.
    I want to search for 'message_box(' but it is not being read due to this '(' special symbol.
    How can I include special symbols in search or replace string?

    So no reply on this thread...
    I will take look at jdapi, but with my poor knowledge of java ......
    JeanYves

  • How to use multiple video files??

    hi all,
    i am using flex 4 ...
    now i have designed video player..
    i used single flv file for execution..
    how to use more flv files in tis program???
    i have included program also..
    can any one reply for this...
    thanks in advance...
    regards,
    saran r
    video.mxml:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="init()" height="700" >
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import mx.core.UIComponent;
                import flash.events.NetStatusEvent;
                import flash.media.Video;
                import flash.net.NetConnection;
                import flash.net.NetStream;
                private var nc:NetConnection;
                private var stream:NetStream;
                public var videoDuration:Number;
                public var nsClient:Object = new Object();
                private var videoComp:Video = new Video();
                private var meta:Object = new Object();
                private var timer:Timer = new Timer(100);
                private var uiComp:UIComponent = new UIComponent();
                private function init():void
                    nc = new NetConnection();
                    nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
                    nc.connect("rtmp://localhost/saran");                 
                    this.addElement(uiComp);
                    uiComp.addChild(videoComp);
                    timer.addEventListener(TimerEvent.TIMER,timerHandler);
                    timer.start();
                private function netStatusHandler(event:NetStatusEvent):void
                    trace("Code ===>>>    "+event.info.code);
                    if(event.info.code == "NetConnection.Connect.Success")
                        connectStream(nc);
                private function connectStream(nc:NetConnection):void {
                    stream = new NetStream(nc);
                    videoComp.attachNetStream(stream);
                    stream.play("Terminator")
                    // stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
                    stream.client = nsClient//new CustomClient();
                    nsClient.onMetaData = metadataHandler;
                    trace("stream ===>>>    "+stream.currentFPS);
                    //responder = new Responder(onResult);
                    // nc.call("getStreamLength", responder, "bikes" );
                private function metadataHandler(metadataObj:Object):void
                    meta = metadataObj;
                    videoComp.width = metadataObj.width;
                    videoComp.height = metadataObj.height;
                    //positionBar.move(videoComp.x, ((videoComp.y + videoComp.height)+20));
                    //positionBar.width = videoComp.width;
                    trace("Duration ====>>>>   "+meta.duration);
                private function timerHandler(event:TimerEvent):void
                    //trace("Timer called.........."+stream.time);
                    //positionBar.setProgress(stream.time, meta.duration);
            ]]>
        </fx:Script>
    </s:Application>

    I have the same question but I am using two pc's

  • Multiple use of properties file

    Is there a way to use a properties file for multiple languages?
    ie.
    en_EN points to the en_EN properties file
    I want en_US to also point to that, is this possible? (it now points to default language if not present)
    And anyone got a good tutorial / overview of the possibilities of properties file? have not been able to find a good example that shows all possibilities
    Thanks

    Provide an en version which contains all the English stuff, then put all the en_US and en_EN variants into those files respectively.

  • How to use my as3 file in flex

    hi, I am new in flex and want to divert into flex. How to  use my as3 file into flex. Is there any sample tutor . so, that I could learn fast.

    Please clarify. Is this .as file a class you previously used as a complonentcomponent you now wish to use as the main application?
    If the .as file just has variables and functions you wish to access from your Flex app, use:
    include "subfolder1/subfolder2/etc/MyASFile.as";
    If you want to use classes from the file, do this:
    import subfolder1.subfolder2.etc.MyClassName;
    If this post answers your question or helps, please mark it as such.
    Greg Lafrance - Flex 2 and 3 ACE certified
    www.ChikaraDev.com
    Flex / AIR Development, Training, and Support Services

  • How to read the properties file available in Server File structure in webdy

    hi all,
    I have developed one webdynpro application. In this application i need to access mdm server to continue. For getting the connection i need to pass the IP addresses.
    Can i have code  how to read the properties file which is residing in the server file. with out included along with the application. keeping some where in the file structure in the server. I want to read that properties file by  maintain the iP addresses and users in  properties file based on the key i want to read like below.
    servername="abcServer"
    username="john"
    password="test123"
    Please send me the code how to read this properties file from the file structure and how to read this values by key  in webdynpro application
    Regards
    Vijay

    Hi Vijay,
    You can try this piece of code too:
    Properties props = new Properties();
    //try retrieve data from file
    //catch exception in case properties file does not exist
    try {
             props.load(new FileInputStream("c:\property\Test.properties")); //File location
             String serverName = props.getProperty("servername"); //Similarly, you can access the other properties
             if(serverName==null)
               //....do appropriate handling
         }     catch(IOException e)
                   e.printStackTrace();
    Regards,
    Alka.

  • How to read from properties file

    Hi,
    I am using JSR 168.
    while creating a new portlet, a folder gets created with the name as "portlet". Under which is resource package and <PortletName>Bundle.java.
    pls tell me how to read from .properties file.
    waiting eagerly for some reply
    Thanks & Regards,
    HP
    Edited by: user9003827 on Apr 13, 2010 3:42 AM

    I think i have mixed it up :)
    I have looked at it again and believe you are using regular JSP portlets.
    Can you tell what you want to achieve by reading .properties file. Are you meaning the preferences of the portlet or what exactly are you trying to do?
    Reading propertie files is easy:
    // Read properties file.
    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("filename.properties"));
        String myKey = properties.getProperty("yourKey");
    } catch (IOException e) {
    }Edited by: Yannick.O on 13-Apr-2010 05:52

  • HOw to access ApplicationResource.properties file using getSystemResource

    I am using struts. I need to access ApplicationResource.properties file, which I define my connection String there. All my methods are static method, so I cannot use getResourceAsStream() method from ClassLoader class, so i have to use getSystemResourceAsStream() method. However, I always get class not found error. Inputstream is always null.
    my ApplicationResource.properties file is stored in projectname/classes, and all my other classes store in projectname/classes/com/testname/. Can anybody tell me how to make it work? Thank you in advance.
    Here is my code:
    private static String getConnectionURL() throws FileNotFoundException,IOException,ClassNotFoundException
    Properties properties = new Properties();
    InputStream fromFile = ClassLoader.getSystemResourceAsStream("ApplicationResources.properties");
    if (fromFile !=null)
    properties.load(fromFile);
    String connectionURL = properties.getProperty("progressiveURL");
    return connectionURL;
    }

    Try either:
    ClassLoader.getSystemResourceAsStream("/ApplicationResources.properties");
    or
    YourClass.class.getResourceAsStream("/ApplicationResources.properties");
    in either case, you need to add the "/" prefix.

  • How to use JDBC Appender of log4j using a properties file

    Hi,
    I am trying to implement the Log4j JDBC Appender to log the messages to Database(oracle).Can anyone provide me with a sample code along with the properties file used.
    need urgent help.
    Thanks in advance

    Actually, I konw where my problem in my code is. Use functions  
    PDDocAcquirePage(), PDPageGetAnnot(),
    PDTextAnnotGetContents(),
    PDTextAnnotGetContents()
    step by step with the logic designed by ourself can finish my task.
    But also thanks for your help!
     

  • How to use portlet backing file if I choose book properties edit table true

    I don't know how to use the property,please tell me!
    thank you

    If you want a backing file to be run while rendering a book, you should specify your file in Backing property of the book. Is that what you are trying to do?

  • Using Multiple Properties Files in Struts Framework

    Hi Everybody!
    I just to know how to use a multiple message-resources files in a Struts Framework.
    I've 2 properties file :
    1. ApplicationResources_A.properties
    2. ApplicationResources_B.propertiesI put the files under WEB-INF/classes dir.
    My configuration in struts-config file something like below:
    <!--  Begin Testing -->
         <message-resources key="A" parameter="ApplicationResources_A" />
         <message-resources key="B" parameter="ApplicationResources_B" />
    <!--  End Testing -->
    </struts-config>
    if my JSP code is like below , this error is thrown:
    org.apache.jasper.JasperException: Cannot find message resources under key A
      <tr>
        <td width="17%">Language A</td>
        <td width="83%"><bean:message bundle="A" key="user.lang.desc"/></td>
      </tr>
      <tr>
        <td width="17%">Language B</td>
        <td width="83%"><bean:message bundle="B"  key="user.lang.desc"/></td>
      </tr>
    but  if I change the  JSP code like below it  work fine:
      <tr>
        <td width="17%">Language A</td>
        <td width="83%"><bean:message key="user.lang.desc"/></td>
      </tr>
      <tr>
        <td width="17%">Language B</td>
        <td width="83%"><bean:message  key="user.lang.desc"/></td>
      </tr>
    In this code , I dont know  which resources file is used.
    So how do I solve this problem. Thanks you.

    I have defined the following:
    struts-config.xml
    <message-resources key="ldap" parameter="com/project/struts/ldap"/>
    Action.java
    In execute method:
    MessageResources messageResources= MessageResources.getMessageResources("com/project/struts/ldap");
    System.out.println("INITIAL_CONTEXT_FACTORY"+messageResources.getMessage("INITIAL_CONTEXT_FACTORY"));
    and it is working, however I have to change "com/project/struts/ldap" value in Action.java file whenever there is any change in name or location of ldap.properties.
    Can I access this properties in such way that I don't have to change parameter path manually in Action.java (modifying in struts-config.xml is okay)? like access through key="ldap" or something.
    Thanks and regards,

  • How to load a properties file?

    Hello Everyone,
    We are experiencing difficulties when trying to load a properties file from a directory other then the one where the servlet is located. We are using the following code for this purpose:
    private final String PROP_FILE_NAME = "my.properties";
    Properties props = new Properties();
    try {
    props.load(getClass().getResourceAsStream(codeBase + PROP_FILE_NAME));
    } catch(IOException e) {
    //handle error ...
    where codeBase is either physical directory path to the properties file or the URL. In either case we get a NullPointer exception which means that file is not found. But when we copy the properties file into the same directory where the servlet resides, everything works fine.
    Does anybody have an idea as to how to resolve our problem?
    Any help will be greatly appreciated!
    Thanks in advance!
    Y.M.

    URLs try to address this issue for cross-platform file reference.
    I'd try doing something like:
    URL u = new URL(codeBase + PROP_FILE_NAME);
    props.load(getClass().getResourceAsStream(u));
    Regards,
    Eric

Maybe you are looking for