programing

Java 속성 파일 사용 방법

minecode 2022. 7. 3. 00:10
반응형

Java 속성 파일 사용 방법

Java 속성 파일로 저장하고 나중에 로드하고 반복하는 구성 값의 키/값 쌍 목록이 있습니다.

질문:

  • 파일을 로드할 클래스와 동일한 패키지에 저장해야 합니까?아니면 파일을 저장할 장소가 있습니까?
  • " " " " " 입니다..txt
  • 코드에 파일을 로드하려면 어떻게 해야 합니까?
  • 그리고 어떻게 하면 안에 있는 가치를 반복할 수 있을까요?

InputStream을 Property에 전달할 수 있기 때문에 파일을 거의 어디에 두더라도 원하는 대로 호출할 수 있습니다.

Properties properties = new Properties();
try {
  properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
  ...
}

다음과 같이 반복합니다.

for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}
  • 원하는 곳에 파일을 저장할 수 있습니다.항아리 파일에 보관하고 싶다면Class.getResourceAsStream() ★★★★★★★★★★★★★★★★★」ClassLoader.getResourceAsStream()을 사용하다파일 시스템에 있으면 조금 더 쉬워집니다.

  • 어떤 확장자라도 상관없습니다만, 제 경험상으로는 .properties가 더 일반적입니다.

  • 를 사용하여 합니다.Properties.loadInputStream ★★★StreamReader(Java 6을 사용하고 있다면 아마 UTF-8을 사용하고,ReaderISO-8859-1의 경우).

  • 수 있어요.Hashtable인가)Properties유래합니다. 예를 을 사용합니다. 예를 들어 사용.keySet()propertyNames().

속성 파일을 클래스 Foo와 같은 패키지에 넣으면 쉽게 로딩할 수 있습니다.

new Properties().load(Foo.class.getResourceAsStream("file.properties"))

속성이 해시 테이블을 확장하면 해시 테이블에서와 같은 방법으로 값을 반복할 수 있습니다.

*.properties 확장자를 사용하면 편집자 지원을 받을 수 있습니다. 예를 들어 Eclipse에는 속성 파일 편집기가 있습니다.

가지 방법으로 글을 수 있습니다.properties 삭제:

  1. 파일을 같은 패키지에 저장합니다.
  2. ..properties내선번호는 사용자가 직접 선택할 수 있습니다.
  3. 는 에 .java.util= > 패지 = >Properties,ListResourceBundle,ResourceBundle②.
  4. 또는 하거나 직접 합니다.Properties ★★★★★★★★★★★★★★★★★」java.lang.System를 누릅니다

ResourceBundle 링크:

 ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
 System.out.println(rb.getString("key"));

Properties 링크:

Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));

속성 파일이 로드됩니다.

Properties prop = new Properties();
InputStream stream = ...; //the stream to the file
try {
  prop.load(stream);
} finally {
  stream.close();
}

모든 컨피규레이션파일이 있는 디렉토리에 .properties 파일을 저장하기 위해 사용합니다.이 파일에 액세스하는 클래스와 함께 저장하지는 않지만 여기에는 제한이 없습니다.

이름은...저는 장황하게 하기 위해 .properties를 사용하지만 원하지 않으면 .properties라고 이름 짓지 마세요.

자산이 유산이 되었습니다.속성보다 기본 설정 클래스가 우선됩니다.

선호 데이터의 계층적 컬렉션에 있는 노드입니다.이 클래스를 통해 응용 프로그램은 사용자 및 시스템 기본 설정 및 구성 데이터를 저장 및 검색할 수 있습니다.이 데이터는 구현 종속 백업 저장소에 영구히 저장됩니다.일반적인 구현에는 플랫 파일, OS 고유의 레지스트리, 디렉토리 서버 및 SQL 데이터베이스가 포함됩니다.이 클래스의 사용자는 백업 스토어의 세부 정보에 신경 쓸 필요가 없습니다.

기반의 String은 " " " 입니다.Preferences클래스에는 Preferences 데이터 저장소에 기본 데이터를 가져오고 저장하는 데 사용되는 여러 가지 메서드가 있습니다.사용할 수 있는 데이터 유형은 다음과 같습니다.

  1. 스트링
  2. 부울
  3. 이중으로 하다
  4. 흘러가다
  5. 인트
  6. 바이트 배열

파일을 하거나 를 사용합니다.getResourceAsStream()클래스 경로에 속성 파일이 있는지 확인합니다.

package com.mypack.test;

import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;

public class PreferencesExample {

    public static void main(String args[]) throws FileNotFoundException {
        Preferences ps = Preferences.userNodeForPackage(PreferencesExample.class);
        // Load file object
        File fileObj = new File("d:\\data.xml");
        try {
            FileInputStream fis = new FileInputStream(fileObj);
            ps.importPreferences(fis);
            System.out.println("Prefereces:"+ps);
            System.out.println("Get property1:"+ps.getInt("property1",10));

        } catch (Exception err) {
            err.printStackTrace();
        }
    }
}

xml 파일:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="user">
<map />
<node name="com">
  <map />
  <node name="mypack">
    <map />
    <node name="test">
      <map>
        <entry key="property1" value="80" />
        <entry key="property2" value="Red" />
      </map>
    </node>
  </node>
</node>
</root>
</preferences>

기본 설정 스토어 내부 관련 이 기사를 참조하십시오.

예제:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file 
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ",";                         //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);

순서:

  1. 파일은 어디에나 저장할 수 있습니다.
  2. 확장이 필요 없습니다.
  3. Montecristo는 이것을 장전하는 방법을 설명했습니다.잘 될 거예요.
  4. property Names()는 반복하기 위한 열거를 제공합니다.

디폴트에서는, Java 는 애플리케이션의 작업 디렉토리에 이 파일을 엽니다(실제로 이 동작은 사용하는 OS 에 의해서 다릅니다).파일을 로드하려면 다음 작업을 수행합니다.

Properties props = new java.util.Properties();
FileInputStream fis new FileInputStream("myfile.txt");
props.load(fis)

따라서 속성 파일에는 모든 파일 확장자를 사용할 수 있습니다.할 수 있습니다만, 「 보존」을 수 있는 어디에나 보존할 수 .FileInputStream.

이와 관련하여 최신 프레임워크를 사용하는 경우 프레임워크는 속성 파일을 여는 추가 방법을 제공할 수 있습니다.를 들어,은 「스프링」을 합니다.ClassPathResourceJAR 파일 내에서 패키지 이름을 사용하여 속성 파일을 로드합니다.

하는 것에 되면, 그 은 「」에 격납됩니다.java.util.Properties ""를 합니다.propertyNames()★★★★★★ 。

Properties

String filename = "sample.properties";
Properties properties = new Properties();

input = this.getClass().getClassLoader().getResourceAsStream(filename);
properties.load(input);

으로, Ethernet, Ethernet에서 .Properties

    for (Entry<Object, Object> entry : properties.entrySet()) {

        System.out.println(entry.getKey() + " => " + entry.getValue());
    }

Java 8에서 모든 속성을 가져옵니다.

public static Map<String, String> readPropertiesFile(String location) throws Exception {

    Map<String, String> properties = new HashMap<>();

    Properties props = new Properties();
    props.load(new FileInputStream(new File(location)));

    props.forEach((key, value) -> {
        properties.put(key.toString(), value.toString());
    });

    return properties;
}

1) 클래스 패스에 속성 파일을 두는 것은 좋지만 프로젝트 내 어디에나 배치할 수 있습니다.

다음은 클래스 경로에서 속성 파일을 로드하고 모든 속성을 읽는 방법입니다.

Properties prop = new Properties();
InputStream input = null;

try {

    String filename = "path to property file";
    input = getClass().getClassLoader().getResourceAsStream(filename);
    if (input == null) {
        System.out.println("Sorry, unable to find " + filename);
        return;
    }

    prop.load(input);

    Enumeration<?> e = prop.propertyNames();
    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        String value = prop.getProperty(key);
        System.out.println("Key : " + key + ", Value : " + value);
    }

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2) 속성 파일의 확장자는 .properties입니다.

다음은 속성을 반복하는 다른 방법입니다.

Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) { 
    String key = (String) eProps.nextElement(); 
    String value = properties.getProperty(key); 
    System.out.println(key + " => " + value); 
}

나는 작년에 이 부동산의 틀에 대해 글을 썼다.또한 속성을 로드하는 여러 가지 방법이 제공되며 강력한 입력도 가능합니다.

http://sourceforge.net/projects/jhpropertiestyp/ 를 참조해 주세요.

JHPropertiesTyped는 개발자에게 강력한 유형의 속성을 제공합니다.기존 프로젝트에 쉽게 통합할 수 있습니다.속성 유형에 대해 큰 시리즈에 의해 처리됩니다.속성 IO 구현을 통해 속성을 한 줄로 초기화할 수 있습니다.개발자에게 고유한 속성 유형 및 속성 IO를 만들 수 있는 기능을 제공합니다.웹 데모도 이용할 수 있습니다.위의 스크린샷입니다.또한 웹 프런트 엔드를 사용하는 경우 속성을 관리하기 위한 표준 구현이 있어야 합니다.

완전한 문서, 튜토리얼, javadoc, FAQ 등은 프로젝트 웹 페이지에서 이용할 수 있습니다.

여기 준비 정적 클래스

import java.io.*;
import java.util.Properties;
public class Settings {
    public static String Get(String name,String defVal){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            FileReader reader = new FileReader(configFile);
            Properties props = new Properties();
            props.load(reader);
            reader.close();
            return props.getProperty(name);
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
            return defVal;
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
            return defVal;
        } catch (Exception ex){
            logger.error(ex);
            return defVal;
        }
    }
    public static Integer Get(String name,Integer defVal){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            FileReader reader = new FileReader(configFile);
            Properties props = new Properties();
            props.load(reader);
            reader.close();
            return Integer.valueOf(props.getProperty(name));
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
            return defVal;
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
            return defVal;
        } catch (Exception ex){
            logger.error(ex);
            return defVal;
        }
    }
    public static Boolean Get(String name,Boolean defVal){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            FileReader reader = new FileReader(configFile);
            Properties props = new Properties();
            props.load(reader);
            reader.close();
            return Boolean.valueOf(props.getProperty(name));
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
            return defVal;
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
            return defVal;
        } catch (Exception ex){
            logger.error(ex);
            return defVal;
        }
    }
    public static void Set(String name, String value){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            Properties props = new Properties();
            FileReader reader = new FileReader(configFile);
            props.load(reader);
            props.setProperty(name, value.toString());
            FileWriter writer = new FileWriter(configFile);
            props.store(writer, Variables.SETTINGS_COMMENT);
            writer.close();
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
        } catch (Exception ex){
            logger.error(ex);
        }
    }
    public static void Set(String name, Integer value){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            Properties props = new Properties();
            FileReader reader = new FileReader(configFile);
            props.load(reader);
            props.setProperty(name, value.toString());
            FileWriter writer = new FileWriter(configFile);
            props.store(writer,Variables.SETTINGS_COMMENT);
            writer.close();
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
        } catch (Exception ex){
            logger.error(ex);
        }
    }
    public static void Set(String name, Boolean value){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            Properties props = new Properties();
            FileReader reader = new FileReader(configFile);
            props.load(reader);
            props.setProperty(name, value.toString());
            FileWriter writer = new FileWriter(configFile);
            props.store(writer,Variables.SETTINGS_COMMENT);
            writer.close();
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
        } catch (Exception ex){
            logger.error(ex);
        }
    }
}

다음은 샘플입니다.

Settings.Set("valueName1","value");
String val1=Settings.Get("valueName1","value");
Settings.Set("valueName2",true);
Boolean val2=Settings.Get("valueName2",true);
Settings.Set("valueName3",100);
Integer val3=Settings.Get("valueName3",100);

다음과 같은 방법으로 속성 파일을 로드할 수 있습니다.

InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
        Properties props =  new Properties();
        props.load(is);

그런 다음 다음과 같은 람다 식을 사용하여 지도에서 반복할 수 있습니다.

props.stringPropertyNames().forEach(key -> {
            System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
        });

내 생각에 다음과 같이 매우 간단하게 할 수 있는 경우에는 다른 방법이 권장되지 않는다.

@PropertySource("classpath:application.properties")
public class SomeClass{

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

간단하지만 그게 제일 좋은 방법이라고 생각해요!!즐거운 시간 되세요.

언급URL : https://stackoverflow.com/questions/1318347/how-to-use-java-property-files

반응형