문제

Java ResourceBundle으로 다음을 수행 할 수 있습니까?

속성 파일에서 ...

example.dynamicresource=You currently have {0} accounts.

런타임에 ...

int accountAcount = 3;
bundle.get("example.dynamicresource",accountCount,param2,...);

결과를 제공합니다

"현재 3 개의 계정이 있습니다."

도움이 되었습니까?

해결책

사용하지 않고 MessageFormat 다음과 같은 클래스

String pattern = bundle.getString("example.dynamicresource");
String message = MessageFormat.format(pattern, accountCount);

다른 팁

자신에, ResourceBundle 부동산 자리 표시자를 지원하지 않습니다. 일반적인 아이디어는 번들에서 얻는 문자열을 가져 와서 MessageFormat, 그런 다음이를 사용하여 매개 변수화 된 메시지를 받으십시오.

사용하는 경우 JSP/JSTL, 그런 다음 결합 할 수 있습니다 <fmt:message> 그리고 <fmt:param> 이를 위해 사용합니다 ResourceBundle 그리고 MessageFormat 덮개 아래.

사용중인 경우 , 그때는 있습니다 ResourceBundleMessageSource 어느 비슷한 일을합니다, 프로그램의 어느 곳에서나 사용할 수 있습니다. 이것 MessageSource 추상화 (결합 MessageSourceAccessor)보다 사용하기가 훨씬 좋습니다 ResourceBundle.

사용중인 뷰 기술에 따라 다양한 방법이 있습니다. "일반 바닐라"자바 (예 : 스윙)를 사용하는 경우 MessageFormat 이전에 응답 한 API. WebApplication 프레임 워크를 사용하는 경우 (사실, 질문 기록을 올바르게 판단하는 경우), 뷰 기술 및/또는 MVC 프레임 워크에 달려 있습니다. 예를 들어 "일반 바닐라"JSP 인 경우 JSTL을 사용할 수 있습니다. fmt:message 이것을 위해.

<fmt:message key="example.dynamicresource">
    <fmt:param value="${bean.accountCount}">
</fmt:message>

예를 들어 JSF 인 경우 사용할 수 있습니다. h:outputFormat 이것을 위해.

<h:outputFormat value="#{bundle['example.dynamicresource']}">
    <f:param value="#{bean.accountCount}">
</h:outputFormat>

가장 좋은 곳은 사용중인 기술/프레임 워크의 문서를 참조하거나 더 적합하고 자세한 답변을 제공 할 수 있도록 여기에서 알리는 것입니다.

스트럿은 멋진 util을 호출합니다 MessageResources 정확히 당신이 요구하는 일을합니다 ....

예를 들어

MessageResources resources = getResources(request, "my_resource_bundle"); // Call your bundle exactly like ResourceBundle.getBundle() method
resources.getMessage("example.dynamicresource",accountCount,param2,...);

한정최대 3 개의 매개 변수 만 허용합니다 (예 : 자원 속성, Param1, ..., Param3).

사용하는 것이 좋습니다 MessageFormat David Sykes가 제안한대로 (3 개 이상의 매개 변수 값을 사용하려는 경우).

추신 그만큼 getResources 방법은 스트럿에서만 사용할 수 있습니다 Action 수업.

영어 이외의 속성 파일을 위해이 작업을 할 수 있다고 생각하지 않습니다.

내 message.properties 파일은 다음 줄이 있습니다.

info.fomat.log.message.start = {0} 형식으로 로그 메시지를 구문 분석하기 시작합니다.

그리고 내 message_fr_fr.properties 파일에는 다음 줄이 있습니다.

info.fomat.log.message.start = a Partir d 'Analyzer le Message Connecter {0} 형식

이 코드는 영어로만 작동합니다

string.format ((String) 메시지 .getString (GlobalConstants.Message_Format_Start), GlobalConstants.str_json));

그렇습니다 아니다 내 언어 / 로케일이 프랑스어 일 때 자리 표시자를 가치로 교체하십시오 :-(

MessageFormat.fomat ()조차 좋지 않습니다

나는 ResourceBundle이 그렇게 할 수 있다고 생각하지 않지만 String은 다음을 수행 할 수 있습니다.

String.format(bundle.getString("example.dynamicresource"), accountCount);

사용할 때 기억하십시오 MessageFormat.format() 이중 견적을 사용해야합니다 ('') 단일 견적을 표현하려는 경우 리소스 번들에서 (').

MessageFormoat#형식 다음과 같은 경우에 작동합니다.

greetingTo=Have Param, saying hello {0}

RB가 ResourceBundle의 인스턴스 인 경우 이와 같은 두 가지 방법을 선언 할 수 있습니다.

/**This is a method that takes the param to substitute the placeholder**/
public String getString(String key, Object... params  ) {
    try {
        return MessageFormat.format(this.RB.getString(key), params);
    } catch (MissingResourceException e) {
        return "[" + key + "]";
    }
}

/**Without a param, this will derectly delegate to ResourceBundle#getString**/
public String getString(String key) {
    try {
        return this.RB.getString(key);
    } catch (MissingResourceException e) {
        return "[" + key + "]";
    }
} 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top