[英]Convert InputStream from ISO-8859-1 to UTF-8
我在 ISO-8859-1 中有一個包含德語變音符號的文件,我需要使用 JAXB 對其進行解組。 但在我需要UTF-8中的內容之前。
@Override
public List<Usage> convert(InputStream input) {
try {
InputStream inputWithNamespace = addNamespaceIfMissing(input);
inputWithNamespace = convertFileToUtf(inputWithNamespace);
ORDR order = xmlUnmarshaller.unmarshall(inputWithNamespace, ORDR.class);
...
我將“文件”作為 InputStream 獲取。 我的想法是讀取 UTF-8 中的文件內容並制作另一個 InputStream 來使用。 這是我嘗試過的:
private InputStream convertFileToUtf(InputStream inputStream) throws IOException {
byte[] bytesInIso = ByteStreams.toByteArray(inputStream);
String stringIso = new String(bytesInIso);
byte[] bytesInUtf = new String(bytesInIso, ISO_8859_1).getBytes(UTF_8);
String stringUtf = new String(bytesInUtf);
return new ByteArrayInputStream(bytesInUtf);
}
我有這 2 個字符串來檢查內容,但即使只是讀取 ISO 文件,它也會在變音符號所在的位置(?)給出問號,並將其轉換為 UTF_8 會給出奇怪的字符,如 1/2 等。
更新
byte[] bytesInIso = ByteStreams.toByteArray(inputWithNamespace);
String contentInIso = new String(bytesInIso);
byte[] bytesInUtf = new String(bytesInIso, ISO_8859_1).getBytes(UTF_8);
String contentInUtf = new String(bytesInUtf);
驗證 contentInIso 打印問號而不是變音符號,並且通過檢查 contentInIso 而不是變音符號,它有像“�”這樣的字符。
@Override
public List<Usage> convert(InputStream input) {
try {
InputStream inputWithNamespace = addNamespaceIfMissing(input);
byte[] bytesInIso = ByteStreams.toByteArray(inputWithNamespace);
String contentInIso = new String(bytesInIso);
byte[] bytesInUtf = new String(bytesInIso, ISO_8859_1).getBytes(UTF_8);
String contentInUtf = new String(bytesInUtf);
ORDR order = xmlUnmarshaller.unmarshall(inputWithNamespace, ORDR.class);
此方法轉換它由另一個名為 processUsageFile 的方法調用:
private void processUsageFile(File usageFile) {
try (FileInputStream fileInputStream = new FileInputStream(usageFile)) {
usageImporterService.importUsages(usageFile.getName(), fileInputStream, getUsageTypeValidated(usageFile.getName()));
log.info("Usage file {} imported successfully. Moving to archive directory", usageFile.getName());
如果我在 UPDATE 語句下編寫代碼並在嘗試后立即將其放入,則第一個 contentInIso 有問號,但 contentInUtf 有變音符號。 然后,通過進入轉換,jabx 會拋出一個異常,即文件有一個過早的行尾。
關於你得到的行為,
String stringIso = new String(bytesInIso);
在這一步中,您通過使用平台的默認字符集解碼指定的字節數組來構造一個新的字符串。
由於這可能不是 ISO_8859_1,我認為您正在查看的字符串在這里變得亂碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.