2 回答

TA貢獻1946條經驗 獲得超3個贊
使用 java 編寫腳本來檢測有問題的行。
AtomicInteger lineno = new AtomicInteger();
Path path = Paths.get("... .xml");
Files.lines(path, StandardCharsets.ISO_8859_1)
.forEach(line -> {
int no = lineno.incrementAndGet();
byte[] b = line.getBytes(StandardCharsets.ISO_8859_1);
try {
new String(b, StandardCharsets.UTF_8);
} catch (Exception e) {
System.out.printf("[%d] %s%n%s%n", no, line, e.getMessage());
//throw new IllegalStateException(e);
}
});
人們可能會認為這是一個數據錯誤。
一般來說,它也可能是錯誤的緩沖讀?。寒斠粋€多字節序列在緩沖區邊界上被破壞時;然后可能會出現兩個錯誤的半序列。在標準庫代碼中不太可能。
為了確保代碼new String(...)不會被 JVM 丟棄,可能:
int sowhat = Files.lines(path, StandardCharsets.ISO_8859_1)
.mapToInt(line -> {
int no = lineno.incrementAndGet();
byte[] b = line.getBytes(StandardCharsets.ISO_8859_1);
try {
return new String(b, StandardCharsets.UTF_8).length();
} catch (Exception e) {
System.out.printf("[%d] %s%n%s%n", no, line, e.getMessage());
throw new IllegalStateException(e); // Must throw or return int
}
}).sum();
System.out.println("Ignore this: " + sowhat);
人們可能會認為這是一個數據錯誤。
一般來說,它也可能是錯誤的緩沖讀?。寒斠粋€多字節序列在緩沖區邊界上被破壞時;然后可能會出現兩個錯誤的半序列。在標準庫代碼中不太可能。
為了確保代碼new String(...)不會被 JVM 丟棄,可能:
int sowhat = Files.lines(path, StandardCharsets.ISO_8859_1)
.mapToInt(line -> {
int no = lineno.incrementAndGet();
byte[] b = line.getBytes(StandardCharsets.ISO_8859_1);
try {
return new String(b, StandardCharsets.UTF_8).length();
} catch (Exception e) {
System.out.printf("[%d] %s%n%s%n", no, line, e.getMessage());
throw new IllegalStateException(e); // Must throw or return int
}
}).sum();
非法的 XML 字符(在 1.0 版中)?[#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]
int sowhat = Files.lines(path, StandardCharsets.ISO_8859_1)
.mapToInt(line -> {
int no = lineno.incrementAndGet();
byte[] b = line.getBytes(StandardCharsets.ISO_8859_1);
if (!legal(b)) {
System.out.printf("[%d] %s%n%s%n", no, line, e.getMessage());
throw new IllegalStateException(e); // Must throw or return int
}
}).sum();
static boolean legal(byte[] bytes) {
String s = new String(bytes, StandardCharsets.UTF_8);
for (char ch : s.toCharArray()) {
int x = ch;
if ((0 <= x && x <= 8) // ASCII control chars
|| (0xB <= x && x <= 0xC)
|| (0xE <= x && x <= 0x1F)
|| (0x7f <= x && x <= 0x84) // DEL + Unicode control chars
|| (0x86 <= x && x <= 0x9F)) {
return false;
}
}
return true;
}
如果這不起作用,我已經讓你足夠長的時間了。拆分文件并驗證零件。

TA貢獻1872條經驗 獲得超4個贊
我使用此代碼將文件轉換為 UTF-8 格式:
File source = new File("C:\\Users\\cc\\eclipse-workspace\\data\\file.xml");
String srcEncoding="ISO-8859-1";
File target = new File("C:\\Users\\cc\\eclipse-workspace\\data\\file2.xml");
String tgtEncoding="UTF-8";
try (
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source), srcEncoding));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding)); ) {
char[] buffer = new char[16384];
int read;
while ((read = br.read(buffer)) != -1)
bw.write(buffer, 0, read);
}
添加回答
舉報