"오늘 우리는 또 다른 새롭고 흥미로운 주제인 속성을 탐구하고 있습니다. "

"Java에서는 프로그램을 유연하고 쉽게 사용자 지정할 수 있도록 만드는 것이 일반적입니다. 즉, 쉽게 구성할 수 있습니다."

"예를 들어, 프로그램은 시간당 한 번씩 특정 디렉터리에서 파일을 복사하고 압축한 다음 이메일로 보냅니다. 이렇게 하려면 프로그램이 파일을 가져올 디렉터리와 이메일 주소를 알아야 합니다. 이러한 데이터는 일반적으로 애플리케이션 코드가 아니라 별도의 속성 파일 에 저장됩니다 ."

이 파일의 데이터는 등호로 구분된 키-값 쌍으로 저장됩니다.

data.properties file
directory = c:/text/downloads
email = zapp@codegym.cc

"기호의 왼쪽에는 이름(키)이 있고 오른쪽에는 값이 있습니다."

"그래서 이것은 HashMap의 일종의 텍스트 표현입니까?"

"일반적으로 그렇습니다."

"이러한 파일 작업의 편의를 위해 Java에는 특수 Properties 클래스가 있습니다. Properties 클래스는 Hashtable<Object,Object>를 상속합니다. 심지어 파일에서 로드할 수 있는 Hashtable로 생각할 수도 있습니다."

"방법은 다음과 같습니다."

방법 설명
void load(Reader reader) Reader 개체가 나타내는 파일에서 속성을 로드합니다.
void load(InputStream inStream) InputStream 개체가 나타내는 파일에서 속성을 로드합니다.
void loadFromXML(InputStream in) XML 파일에서 속성 로드
Object get(Object key) 지정된 키의 값을 반환합니다. 이 메서드는 Hashtable에서 상속됩니다.
String getProperty(String key) 키로 속성 값(문자열)을 반환합니다.
String getProperty(String key, String defaultValue) 해당 키가 없는 경우 key 또는 defaultValue로 속성 값을 반환합니다.
Set<String> stringPropertyNames() 모든 키 목록을 반환합니다.

"즉, 실제로 두 가지 작업만 수행하면 됩니다. 일부 파일에서 Properties 개체로 데이터를 로드한 다음 getProperty () 메서드를 사용하여 이러한 속성을 가져옵니다. 음, 다음과 같이 Properties 개체를 사용할 수 있다는 것을 잊지 마십시오. 해시 ."

"여기 또 다른 예가 있습니다."

암호
// The file that stores our project's properties
File file = new File("c:/data.properties");

// Create a Properties object and load data from the file into it.
Properties properties = new Properties();
properties.load(new FileReader(file));

// Get property values from the Properties object
String email = properties.getProperty("email");
String directory = properties.getProperty("directory");

// Get a numeric value from the Properties object
int maxFileSize = Integer.parseInt(properties.getProperty("max.size", "10000"));

"아. 그래서 우리는 Properties 개체를 생성한 다음 여기에 파일을 전달합니다. load 메서드에 전달합니다. 그런 다음 getProperty를 호출합니다. 맞습니까?"

"네."

"그리고 HashMap으로 사용할 수 있다고도 하셨습니까? 무슨 뜻입니까?"

"Properties 클래스는 HashMap과 동일한 Hashtable을 상속하지만 모든 메소드가 동기화됩니다. 다음과 같이 속성 파일의 모든 값을 화면에 간단히 표시할 수 있습니다."

암호
// Get the file with the properties
File file = new File("c:/data.properties");

// Create a Properties object and load data from the file into it.
Properties properties = new Properties();
properties.load(new FileReader(file));

// Run through all the keys and display their values on the console
for (String key : properties.stringPropertyNames())
{
 System.out.println(properties.get(key));
}

"아. 모든 것이 제자리를 찾은 것 같습니다. 감사합니다, 리시. 이 멋진 것을 사용하겠습니다."