[英]Reading from property file containing utf 8 character
我正在閱讀一個屬性文件,其中包含 UTF-8 字符集中的消息。
問題
output 的格式不正確。 我正在使用InputStream
。
屬性文件看起來像
username=LBSUSER
password=Lbs@123
url=http://localhost:1010/soapfe/services/MessagingWS
timeout=20000
message=Spanish character are = {á é í, ó,ú ,ü, ñ, ç, å, Á, É, Í, Ó, Ú, Ü, Ñ, Ç, ¿, °, 4° año = cuarto año, €, ¢, £, ¥}
我正在閱讀這樣的文件,
Properties props = new Properties();
props.load(new FileInputStream("uinsoaptest.properties"));
String username = props.getProperty("username", "test");
String password = props.getProperty("password", "12345");
String url = props.getProperty("url", "12345");
int timeout = Integer.parseInt(props.getProperty("timeout", "8000"));
String messagetext = props.getProperty("message");
System.out.println("This is soap msg : " + messagetext);
上述消息的output為
您可以在該行之后的控制台中看到消息
{************************ SOAP MESSAGE TEST***********************}
如果我能在正確閱讀此文件時獲得任何幫助,我將不勝感激。 我可以用另一種方法讀取這個文件,但我正在尋找更少的代碼修改。
將InputStreamReader
與Properties.load(Reader reader)
:
FileInputStream input = new FileInputStream(new File("uinsoaptest.properties"));
props.load(new InputStreamReader(input, Charset.forName("UTF-8")));
作為一種方法,這可能類似於以下內容:
private Properties read( final Path file ) throws IOException {
final var properties = new Properties();
try( final var in = new InputStreamReader(
new FileInputStream( file.toFile() ), StandardCharsets.UTF_8 ) ) {
properties.load( in );
}
return properties;
}
不要忘記關閉你的流。 Java 7 引入了StandardCharsets.UTF_8
。
使用props.load(new FileReader("uinsoaptest.properties"))
代替。 默認情況下,它使用編碼Charset.forName(System.getProperty("file.encoding"))
可以使用System.setProperty("file.encoding", "UTF-8")
或命令行設置為 UTF-8參數-Dfile.encoding=UTF-8
。
如果有人使用 @Value 注釋,可以嘗試 StringUils。
@Value("${title}")
private String pageTitle;
public String getPageTitle() {
return StringUtils.toEncodedString(pageTitle.getBytes(Charset.forName("ISO-8859-1")), Charset.forName("UTF-8"));
}
您應該在構造 FileInputStream 對象時指定 UTF-8 編碼。 您可以使用此構造函數:
new FileInputStream("uinsoaptest.properties", "UTF-8");
如果您想對 JVM 進行更改以便能夠默認讀取 UTF-8 文件,則必須將 JVM 選項中的 JAVA_TOOL_OPTIONS 更改為如下所示:
-Dfile.encoding=UTF-8
如果有人在Kotlin中遇到這個問題,就像我一樣:@Würgspaß 的公認解決方案也適用於此。 對應的 Kotlin 語法:
而不是通常的
val properties = Properties()
filePath.toFile().inputStream().use { stream -> properties.load(stream) }
我不得不使用
val properties = Properties()
InputStreamReader(FileInputStream(filePath.toFile()), StandardCharsets.UTF_8).use { stream -> properties.load(stream) }
這樣,特殊的 UTF-8 字符就會從filePath
中給出的屬性文件中正確加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.