Thursday, June 21, 2018

How to use property file in Java

property file is use for store data which need to change outside of the project.This is an example for use property file.

the property file is saved in "setting/setting.properties"

property file

setting.properties
# To change this license header, choose License Headers in Project Properties. 
# To change this template file, choose Tools | Templates # and open the template in the editor.  
ip=127.0.0.1 
port=6262 


Code


Main.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package rubictron.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.stage.Stage;

/**
 *
 * @author rubictron
 */
public class Main extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        FileReader reader=null;
        try {

            Properties setting=new Properties();//create new property

            File file=new File("setting/setting.properties");//get file
            reader = new FileReader(file);//read file
            setting.load(reader);//load file to property
            System.out.println("ip= "+setting.getProperty("ip"));
            System.out.println("port= "+setting.getProperty("port"));
            
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}




No comments:

Post a Comment