Property file in java project

where to put the properties file in an eclipse project

Please tell me where exactly do i put my .properties file in my eclipse project. Do I make a separate folder for it ? I want to put it in such a way that I will be able to distribute my project easily in JAR form. Thanks. EDIT: I want to put the properties file in such a way that it can be easily edited later, on any OS.

That’s one way. The key thing is: How does your code access it? You can’t use a FileInputStream; you need to use getResourceAsStream() to get it from the classpath using the class loader.

2 Answers 2

The approach I use in order to be able to easily change configuration without redeployment.

One version of the property file (with the defaults) in the root of your project, I always let it in the application package (foo.bar.myapp). I load the default one with getResourceAsStream(«/foo/bar/myapp/config.properties») or like in the sample relative to the class package.

And additionally I ready a system property:

String configFileLocation = System.getProperty("config"); 

And just override the default with the properties read from the config file passed as property.

Properties props = new Properties(); props.load(Main.class.getResourceAsStream("mydefault.properties")); System.out.println("default loaded: " + props); String configFile = System.getProperty("config"); if (configFile != null) < props.load(new FileInputStream(configFile)); System.out.println("custom config loaded from " + configFile); >System.out.println("custom override: " + props); 

This would load first your resource stored under your project in foo.bar package named mydefault.properties , and after it if system property config is configured it will load override the loaded properties with the one the the referred path.

Читайте также:  Javascript получить option value

The system property can be set using -D parameter, in this case would be something like: java -Dconfig=/home/user/custom.properties foo.bar.Main . Or if you are in a web application (Tomcat for instance) you can set this property using CATALINA_OPTS .

Источник

How to add a Java Properties file to my Java Project in Eclipse

I was using Unix before to compile and edit my Java. In that I have used property files right inside my current working directory where the class file exists. Now i have switched to Eclipse IDE. I dont know how to add the same properties file here in Eclipse. Please help me.

8 Answers 8

  1. Create Folder “resources” under Java Resources folder if your project doesn’t have it.
    1. create config.properties file with below value.

    enter image description here

    Properties prop = new Properties(); InputStream input = null; try < input = getClass().getClassLoader().getResourceAsStream("config.properties"); // load a properties file prop.load(input); // get the property value and print it out System.out.println(prop.getProperty("database")); System.out.println(prop.getProperty("dbuser")); System.out.println(prop.getProperty("dbpassword")); >catch (IOException ex) < ex.printStackTrace(); >finally < if (input != null) < try < input.close(); >catch (IOException e) < e.printStackTrace(); >> > 

    In the package explorer, right-click on the package and select New -> File, then enter the filename including the «.properties» suffix.

    This does not work anymore. There is no simple file option after selecting New > . You are forced to choose either a .HTML or .JSP file (and appropriate file extensions for naming) and you are blocked from naming it with .properties . Any suggestions?

    @Mowzer: what file types are listed directly depends on what eclipse edition you have and maybe even configuration. Apparently you’re using one targeted at web development. But you can still choose «other» to get to the plain file option.

    It should work ok as it is in Unix, if you have properties file in current working directory. Another option would be adding your properties file to the classpath and getting the inputstream using this.getClass().getClassLoader().getResourceAsStream(«xxxxx.properties»); More here

    1. Right click on any package where you want to create your .properties file or create a new package as required
    2. now select new then select file (if you dont find file then go to location of your package and create it there)
    3. now named it as yourfilename.properties

    If you have created a Java Project in eclipse by using the ‘from existing source’ option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select ‘Create project from existing source‘ and then select your existing project folder. The wizard will take care of the rest.

    1. Right click on the folder within your project in eclipse where you want to create property file
    2. New->Other->in the search filter type file and in the consecutive window give the name of the file with .properties extension

    To create a property class please select your package where you wants to create your property file.

    Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.

    If you are working with core java, create your file(. properties ) by right clicking your project. If the file is present inside your package or src folder it will throw an file not found error

    Источник

    Placing a properties file in a java project

    I am having some trouble understanding where to place a properties file in a java project. I have the following project structure .

    src. | java | test.properties | a.java Parameters.properties 
     Properties prop = new Properties(); try < InputStream in = this.getClass().getResourceAsStream("Parameters.properties"); // load a properties file prop.load(in); // get the property value and print it out System.out.println(prop.getProperty("hello.world")); >catch (IOException ex)

    I keep getting a null pointer error which leads me to believe it is not able to read the file because it has not got the file yet .

    2 Answers 2

    You need to put your file Parameters.properties not in src folder, but in built or target folder. Or for simple explanation find a.class file and put Parameters.properties in the same folder.

    built. | java | test.properties | a.class Parameters.properties 

    Because when you use getClass() method you get binary file with .class extension and search resources in folder where this file is.

    1.) One way of doing this is — Add your properties file in any source folder. A source folder is a folder that is included in class path. e.g. src/ A.java Create another Source folder

    at src level and place file here

    And in A.java acces like this File file = new File(«.//resources//params.properties»);

    2.) Another easy way Add properties file in src folder, and Right click on properties file -> build Path ->Add to Class Path.

    And Access file in A.java like this.

    File file = new File("params.properties"); 

    Источник

    Java Property File Processing

    Properties is a file extension for files mainly used in Java related technologies to store the configurable parameters of an application. Java Properties files are amazing resources to add information in Java. Generally, these files are used to store static information in key and value pair. Things that you do not want to hard code in your Java code goes into properties files. The advantage of using properties file is we can configure things which are prone to change over a period of time without the need of changing anything in code. Properties file provide flexibility in terms of configuration. Sample properties file is shown below, which has information in key-value pair.

    Each parameter is stored as a pair of strings, left side of equal (=) sign is for storing the name of the parameter (called the key), and the other storing the value.

    Configuration:

    This is property file having my configuration FileName=Data.txt Author_Name=Amit Himani Website=w3resource.com Topic=Properties file Processing 

    First Line which starts with # is called comment line. We can add comments in properties which will be ignored by java compiler.

    Below is the java program for reading above property file.

    package propertiesfile; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class PropertyFileReading < public static void main(String[] args) < Properties prop = new Properties(); try < // load a properties file for reading prop.load(new FileInputStream("myConfig.properties")); // get the properties and print prop.list(System.out); //Reading each property value System.out.println(prop.getProperty("FileName")); System.out.println(prop.getProperty("Author_Name")); System.out.println(prop.getProperty("Website")); System.out.println(prop.getProperty("TOPIC")); >catch (IOException ex) < ex.printStackTrace(); >> > 

    The program uses load( ) method to retrieve the list. When the program executes, it first tries to load the list from a file called myConfig.properties. If this file exists, the list is loaded else IO exception is thrown.

    directory structure image

    If File is not present in default project root location, we will get an exception like below, We can provide a fully qualified path of the file as well.

    directory structure image

    Use of getProperties() Method

    One useful capability of the Properties class is that you can specify a default property that will be returned if no value is associated with a certain key. For example, a default value can be specified along with the key in the getProperty( ) method—such as getProperty(“name”,“default value”). If the “name” value is not found, then “default value” is returned. When you construct a Properties object, you can pass another instance of Properties to be used as the default properties for the new instance.

    Writing Properties file

    At any time, you can write a Properties object to a stream or read it back. This makes property lists especially convenient for implementing simple databases. For Example below program writes states can capital cities. “capitals.properties” file having state name as keys and state capital as values.

    package propertiesfile; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class PropertyFileWriting < public static void main(String args[]) < Properties prop = new Properties(); try < // set the properties value prop.setProperty("Gujarat", "Gandhinagar"); prop.setProperty("Maharashtra", "Mumbai"); prop.setProperty("Madhya_Pradesh", "Indore"); prop.setProperty("Rajasthan", "Jaipur"); prop.setProperty("Punjab", "mkyong"); prop.setProperty("Uttar_Pradesh", "Lucknow"); // save properties to project root folder prop.store(new FileOutputStream("capitals.properties"), null); >catch (IOException ex) < ex.printStackTrace(); >> > 

    After running the program we can see a new file created named “capitals.properties” under project root folder as shown below.

    Web Apr 24 19:50:18 IST 2013 Uttar_Pradesh=Lucknow Madhyar_Pradesh=Indore Maharashtra=Mumbai Gujarat=Gandhinagar Panjab=mkyong Rajasthan=jaipur
    • Properties file provide flexibility in terms of configuration in java based application.
    • We can store information in a properties file which can be changed over a period of time like database connection properties, password, input file name or location etc.
    • We can Read/Write property file using java.util.Properties library of Java.

    Java Code Editor:

    Previous: Writing file
    Next: Java Serialization

    Follow us on Facebook and Twitter for latest update.

    • Weekly Trends
    • Java Basic Programming Exercises
    • SQL Subqueries
    • Adventureworks Database Exercises
    • C# Sharp Basic Exercises
    • SQL COUNT() with distinct
    • JavaScript String Exercises
    • JavaScript HTML Form Validation
    • Java Collection Exercises
    • SQL COUNT() function
    • SQL Inner Join
    • JavaScript functions Exercises
    • Python Tutorial
    • Python Array Exercises
    • SQL Cross Join
    • C# Sharp Array Exercises

    We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

    Источник

Оцените статью