[Java] Properties

JTI·2023년 1월 20일
0

☕️  Java

목록 보기
55/59
post-thumbnail

💡 Properties


✔️ Hashtable 을 상속받아 구현한 것으로, Properties(String, String) 형태로 저장한다.

String 형태이기 때문에 get()set(), put() 을 제공한다.

  • "Key = Value" 형태로 된 "파일이름.properties" 파일 또는 xml 파일

  • 주로 애플리케이션의 환경설정과 관련된 속성을 저장하는데 사용되며 파일로부터 읽고 쓰는 편리한 기능을 제공한다.

  • DB에 대한 연결정보를 파일로 저장해놓고 사용하는 용도로 많이 쓰인다.

  • 코드를 건들이지 않고도 정보를 변경할 수 있다는 장점이 있다.

📎 생성

  • 파일을 직접 여는 클래스가 아니므로 FileReader 또는 FileInputStream 객체를 매개변수로 받는다.

  • 외부 리소스와 연결되지 않으므로 '확인된 예외'가 throw되어 있지 않다.

  • load() 메서드를 통해 파일 정보를 넣어준다.

✏️ Properties 메서드


✏️ Properties 값(value) 가져오기_ 읽기


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

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

        FileInputStream fis = null;

        try {
        	// FileInputStream 생성
            fis = new FileInputStream("prop.txt");
			
            // properties 생성
            Properties prop = new Properties();
            
     	    // 파일을 열어서 읽어줌
            prop.load(fis);

            System.out.println(prop);
            
            // getProperty(): 키에 해당하는 Value를 가져옴
            System.out.println(prop.getProperty("1"));
            System.out.println(prop.getProperty("2"));


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeAll(fis);
        }

    }

}
{1=1Value, 2=2Value, 3=3Value, 4=4Value, 5=5Value}
1Value
2Value

✏️ Properties 파일 생성_ 쓰기


  • 파일을 직접 생성하지 못하므로 FileOutputStream 또는 FileWriter 로 파일 생성

  • 파일 생성 후, 메서드를 사용해서 내용을 입력한다.

  • 파일 생성은 Stream 클래스 계열로 하고 Properties 클래스의 메서드로 내용만 넣어준다.

❗️ 일반 파일 쓰기로 만든것과 달리 주석을 넣어줘야 하며 생성한 날짜도 자동으로 쓰여진다.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesEx1 {
    public static void main(String[] args) {
        Properties prop = new Properties();

        // Object setProperty(): Properties 객체에 키와 값을 저장
        prop.setProperty("1", "1Value");
        prop.setProperty("2", "2Value");
        prop.setProperty("3", "3Value");
        prop.setProperty("4", "4Value");
        prop.setProperty("5", "5Value");

        // 파일을 직접 생성하지 못하므로 FileOutputStream 또는 FileWriter로 파일 생성
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream("prop.txt");

            // 객체에 저장된 내용을 파일에 씀(OutputStream 또는 Writer 계열만 가능)
            prop.store(fos, "made in JTI"); // store(스트림객체, 주석)

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeAll(fos);
        }


    }
}
#made in JTI
#Fri Jan 20 22:24:43 KST 2023
1=1Value
2=2Value
3=3Value
4=4Value
5=5Value

📎 prop.storeToXML()

❗️ xml 파일로도 저장 가능하다

fos = new FileOutputStream("mySetting.xml");


✏️ Properties Value 값 수정


  • key의 추가나 수정은 setProperty() 를 통해서 한다.
  • key값이 없을 경우 추가되며, 있을 경우 수정이 된다.
prop.setProperty(String, String)

❗️ key, value 값을 영속적으로 바꿀려면 store() 을 한번 더 써줘야 한다.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesEx1 {
    public static Properties prop = new Properties();

    public static void write() {
        prop.setProperty("first", "1");
        prop.setProperty("second", "2");
        prop.setProperty("third", "3");

        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream("propEx.txt");
            prop.store(fos, "from JTI");
            System.out.println(prop);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {}
        }

    }

    public static void read() {
        FileInputStream fis = null;

        try {
            fis = new FileInputStream("propEx.txt");
            prop.load(fis);

            System.out.println(prop);

        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e3) {}
        }
    }
    
    public static void changes(String num, int intNum) {
        String strNum = String.valueOf(intNum);
        prop.setProperty(num, strNum);

        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream("propEx.txt");

            prop.store(fos, "from JTI");

        } catch (IOException e) {

        } finally {
            try {
                fos.close();
            } catch (IOException e) {}
        }
        System.out.println(prop);
    }

    public static void main(String[] args) {
        write();
        changes("first", 5);
        read();
    }
}
{third=3, second=2, first=1}
{third=3, second=2, first=5}
{third=3, second=2, first=5}

✏️ Properties key값만 들고오기


  • keySet Set을 반환하며 String[]로 만들어서 반환할 수 있다.
String[] keys = prop.keySet().toArray(new String[0]);
	public static void getkeys() {
        String[] keys = prop.keySet().toArray(new String[0]);

        for(String key : keys) {
            System.out.println(key);
        }
    }

    public static void main(String[] args)  {
        getkeys();
    }
third
second
first

References
: https://codevang.tistory.com/163

profile
Fill in my own colorful colors🎨

0개의 댓글