LoginSignup
29
30

More than 5 years have passed since last update.

Java properties ファイルからの値の取得

Posted at

Java勉強中にて、初歩的なところから。
設定ファイル的なやつから値をどうやって読み込むのが良いのかなと思って調べた方法。

本当は ini ファイル形式のほうがよかったけど、とりあえず、key valueで取れれば良し。

sample.properties

id = some_id
password = some_password

ConfigTest.java

import java.util.Properties;
import java.io.FileInputStream;
import java.io.InputStream;

public class ConfigTest {
    public static void main (String[] args) {

        Properties properties = new Properties();

        String file = "/tmp/sample.properties";
        try {
            InputStream inputStream = new FileInputStream(file);
            properties.load(inputStream);
            inputStream.close();

            // 値の取得
            System.out.println(properties.getProperty("id"));
            System.out.println(properties.getProperty("password"));

        } catch (Exception ex) {
            System.out.println(ex.getMessage());

        }

    }
}

ちなみに、phpだと、下記だけですむ。

<?php
$config = parse_ini_file("sample.properties");
echo $config['id'] ."\n";
echo $config['password'] ."\n";
29
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
30