[英]How to format java shell output stream by removing illegal characters
[英]How to read a string stream in Java discarding illegal characters?
我必須解析來自TCP連接的字節流,該連接應該只給我可打印的字符,但實際上並非總是這樣。 我在那里看到了一些二進制零,在某些字段的開頭和結尾。 我無法控制數據源,我需要處理“臟”行。 如果我可以過濾掉無效字符,那就沒問題了。 相關代碼如下:
srvr = new ServerSocket(myport);
skt = srvr.accept();
// Tried with no encoding argument too
in = new Scanner(skt.getInputStream(), "ISO-8859-1");
in.useDelimiter("[\r\n]");
for (;;) {
String myline = in.next();
if (!myline.equals(""))
ProcessRecord(myline);
}
我在每條有“污垢”的行都會遇到異常。 什么是過濾掉無效字符同時仍然能夠獲得其余字符串的好方法?
您必須將您的InputStream
包裝在CharsetDecoder
,定義一個空的錯誤處理程序:
//let's create a decoder for ISO-8859-1 which will just ignore invalid data
CharsetDecoder decoder=Charset.forName("ISO-8859-1").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
//let's wrap the inputstream into the decoder
InputStream is=skt.getInputStream();
in = new Scanner(decoder.decode(is));
您還可以使用自定義CodingErrorAction
並在編碼錯誤時定義您自己的操作。
最純粹的解決方案是過濾InputStream(二進制字節級I / O)。
in = new Scanner(new DirtFilterInputStream(skt.getInputStream()), "Windows-1252");
public class DirtFilterInputStream extends InputStream {
private InputStream in;
public DirtFilterInputStream(InputStream in) {
this.in = in;
}
@Override
public int read() throws IOException {
int ch = in.read();
if (ch != -1) {
if (ch == 0) {
ch = read();
}
}
return ch;
}
}
(您需要覆蓋所有方法,並委托給原始流。)Windows-1252是Windows Latin-1,擴展拉丁語1,ISO-8859-1,使用0x80 - 0xBF。
我完全偏離了基地。 我得到“臟”字符串沒有問題(不,我沒有選項來清理數據源,它來自一個封閉的系統,我不得不笑着處理它)但是試圖將它們存儲在PostgreSQL中是得到的我是例外。 這意味着我可以在處理之前完全自由地清理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.