search
LoginSignup
32
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Organization

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

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";

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
What you can do with signing up
32
Help us understand the problem. What are the problem?