- Java properties files parameters
- Простой пример работы с Property файлами в Java
- Шаг 0. Создание проекта
- Шаг 2. Добавляем конфигурационные данные в проперти файл
- Шаг 3. Получаем Property данные
- Java Properties File: How to Read config.properties Values in Java?
- We will create 3 files:
- Let’s get started:
- Step-1: Create config.properties file.
- /Java Resources/config.properties file content:
- Step-2
- Step-3
- Step-4
- Are you running above program in IntelliJ IDE and getting NullPointerException?
- Suggested Articles.
Java properties files parameters
In this tutorial, you will learn how to use Java properties file to pass parameters to the java application. Four Java code examples show different approaches to the solution of the problem and explain how to write Java code that read parameters from a properties file. Read Start Java Programming tutorial to learn how to configure your PC to be able to run java application.
Copy Greeting2.java source code and paste it in notepad or your favorite editor for plain text. (Do not use MS World). I like TextPad editor. It allows you to use regular expression for search and replace. It displays the text line number. It can compile and run Java Application
Greeting2.java import java.io.*; import java.util.*; public class Greeting2 < String message; // class constructor public Greeting2() < >public void setMessage() < //create an instance of properties class Properties props = new Properties(); //try retrieve data from file try < props.load(new FileInputStream("message.properties")); message = props.getProperty("message"); System.out.println(message); >//catch exception in case properties file does not exist catch(IOException e) < e.printStackTrace(); >> public static void main(String[] args) < //create an instance of greeting2 class Greeting2 gr = new Greeting2(); //call the setMessage() method of the Greeting2 class gr.setMessage(); >> //end of source code file Save the Greeting2.java file in "C:\java\prop" directory Compile the source file Greeting2.java C:\java\prop>javac Greeting2.java Execute Greeting2 Java application C:\java\prop>java Greeting2 java.io.FileNotFoundException: message.properties (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:106) at java.io.FileInputStream.(FileInputStream.java:66) at Greeting2.setMessage(Greeting2.java:37) at Greeting2.main(Greeting2.java:60) C:\java\prop>
Input-Output Exception is thrown because of the message.properties file does not exist.
Let us create it. Open Notepad and type the following text.
Save the file as message.properties in C:\java\prop directory.
Try to execute Greeting2 application again.
Now our message is displayed. Open message.properties file and delete the text:
Try to execute Greeting2 application again.
null will display instead of the message
To improve our program let us add default message,
just in case if something will go wrong with getting the message from file
Improved our greeting class
import java.io.*; import java.util.*; public class Greeting3 < String message; public Greeting3() < >public void setMessage() < //create an instance of properties class Properties props = new Properties(); //try retrieve data from file //catch exception in case properties file does not exist try < props.load(new FileInputStream("message.properties")); message = props.getProperty("message"); //If value of message variable is null assign default value "Hello World" if(message==null) System.out.println(message); > //catch exception in case properties file does not exist catch(IOException e) < e.printStackTrace(); >> public static void main(String[] args) < //create an instance of Greeting3 class Greeting3 gr = new Greeting3(); //call the setMessage() method of the Greeting3 class gr.setMessage(); >>
Compile the source file Greeting3.java
Execute Greeting3 Java application
Open message.properties file and enter text
Execute Greeting3 Java application again
«How are you» message displays
Let us improve the application. Set default message in class constractor.
import java.io.*; import java.util.*; public class Greeting4 < String message; public Greeting4() < message= new String("Hello World"); >public void setMessage() < //create an instance of properties class Properties props = new Properties(); //try retrieve data from file try < props.load(new FileInputStream("message.properties")); // assign value to message variable only if it is not null if(props.getProperty("message") !=null) System.out.println(message); > //catch exception in case properties file does not exist catch(IOException e) < System.out.println(message); >> public static void main(String[] args) < //create an instance of Greeting4 class Greeting4 gr = new Greeting4(); //call the setMessage() method of the Greeting4 class gr.setMessage(); >>
Compile the source file Greeting4.java
Execute Greeting4 Java application
Open message.properties file and delete text «message = How are you.»
Download the complete source code for a responsive website with user registration and authentication.
Execute Greeting4 Java application again
Delete message.properties file
Execute Greeting4 Java application again
Hello World default message will be displayed in both cases.
Простой пример работы с Property файлами в Java
Property файлы присутствуют практически в каждом проекте, и сейчас я вам покажу простой пример их использования, а также расскажу, зачем они и где используются.
Шаг 0. Создание проекта
Начнем с того что создадим простой Maven проект, указав название и имя пакета:
Структура, которая получится в конце проекта довольно таки простая.
Как видите у нас только два файла, первый – Main.java, а второй – config.properties.
Шаг 2. Добавляем конфигурационные данные в проперти файл
Проперти файлы либо файлы свойств – предназначены, для того чтобы хранить в них какие-то статические данные необходимые проект, например логин и пароль к БД.
Давайте добавим в наш config.properties логин и пароль (это любые данные, для того чтобы продемонстрировать работу с property файлами).
Содержимое config.properties:
db.host = http://localhost:8888/mydb db.login = root db.password = dbroot
ключ> – это уникальное имя, по которому можно получить доступ к значению, хранимому под этим ключом.
значение> – это текст, либо число, которое вам необходимо для выполнения определённой логики в вашей программе.
Шаг 3. Получаем Property данные
Как можно видеть в структуре проекта выше, там есть класс Main.java давайте его создадим и напишем в нем следующее:
package com.devcolibir.prop; import java.io.*; import java.util.Properties; public class Main < public static void main(String[] args) < FileInputStream fis; Properties property = new Properties(); try < fis = new FileInputStream("src/main/resources/config.properties"); property.load(fis); String host = property.getProperty("db.host"); String login = property.getProperty("db.login"); String password = property.getProperty("db.password"); System.out.println("HOST: " + host + ", LOGIN: " + login + ", PASSWORD: " + password); >catch (IOException e) < System.err.println("ОШИБКА: Файл свойств отсуствует!"); >> >
Обращаясь к property.getProperty(ключ>) – вы получаете его значение.
Вот такой краткий, но думаю познавательный урок.
Java Properties File: How to Read config.properties Values in Java?
.properties is a file extension for files mainly used in Java related technologies to store the configurable parameters of an application. They can also be used for storing strings for Internationalization and localization; these are known as Property Resource Bundles.
Each parameter is stored as a pair of strings, one storing the name of the parameter (called the key/map ), and the other storing the value.
Below is a sample Java program which demonstrate you how to retrieve/read config.properties values in Java. For update follow this tutorial.
We will create 3 files:
- CrunchifyReadConfigMain.java
- CrunchifyGetPropertyValues.java
- config.properties file
Main Class (CrunchifyReadConfigMain.java) which will call getPropValues() method from class CrunchifyGetPropertyValues.java .
Let’s get started:
Step-1: Create config.properties file.
- Create Folder “ resources ” under Java Resources folder if your project doesn’t have it.
- create config.properties file with below value.
/Java Resources/config.properties file content:
#Crunchify Properties user=Crunchify company1=Google company2=eBay company3=Yahoo
Step-2
Create file CrunchifyReadConfigMain.java
package crunchify.com.tutorial; import java.io.IOException; /** * @author Crunchify.com * */ public class CrunchifyReadConfigMain < public static void main(String[] args) throws IOException < CrunchifyGetPropertyValues properties = new CrunchifyGetPropertyValues(); properties.getPropValues(); >>
Step-3
Create file CrunchifyGetPropertyValues.java
package crunchify.com.tutorial; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; /** * @author Crunchify.com * */ public class CrunchifyGetPropertyValues < String result = ""; InputStream inputStream; public String getPropValues() throws IOException < try < Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) < prop.load(inputStream); >else < throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); >Date time = new Date(System.currentTimeMillis()); // get the property value and print it out String user = prop.getProperty("user"); String company1 = prop.getProperty("company1"); String company2 = prop.getProperty("company2"); String company3 = prop.getProperty("company3"); result = "Company List = " + company1 + ", " + company2 + ", " + company3; System.out.println(result + "\nProgram Ran on " + time + " by user=" + user); > catch (Exception e) < System.out.println("Exception: " + e); >finally < inputStream.close(); >return result; > >
Step-4
Run CrunchifyReadConfigMain and checkout result.
Company List = Google, eBay, Yahoo Program Ran on Mon May 13 21:54:55 PDT 2013 by user=Crunchify
As usually happy coding and enjoy. Do let me know if you see any exception. List of all Java Tutorials.
Are you running above program in IntelliJ IDE and getting NullPointerException?
Please follow below tutorial for fix.
If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.