从ac套接字向java套接字发送UTF8字符串时遇到了一些麻烦.以下方法工作正常:
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
main.title = in.readLine();
Run Code Online (Sandbox Code Playgroud)
但后来我需要int java.io.InputStream.read(byte[] b, int offset, int length)一个BufferedReader不存在的方法.那么我试着采用DataInputStream
DataInputStream in2 = new DataInputStream(socket.getInputStream());
Run Code Online (Sandbox Code Playgroud)
但它所读的一切都只是垃圾.
然后我尝试使用该readLine()方法,DataInputStream但这并没有给我正确的UTF8字符串.
你看到了我的困境.我不能为一个InputStream使用两个读卡器吗?或者我可以转换DataInputStream.readLine()结果并将其转换为UTF8吗?
谢谢,马丁
我们从UTF-8编码的设计中知道,该值的唯一用途0x0A是LINE FEED('\n').因此,您可以阅读,直到您点击它:
/** Reads UTF-8 character data; lines are terminated with '\n' */
public static String readLine(InputStream in) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while (true) {
int b = in.read();
if (b < 0) {
throw new IOException("Data truncated");
}
if (b == 0x0A) {
break;
}
buffer.write(b);
}
return new String(buffer.toByteArray(), "UTF-8");
}
Run Code Online (Sandbox Code Playgroud)
我假设您的协议\n用作行终止符.如果不是 - 那么指出你写的约束通常很有用.
| 归档时间: |
|
| 查看次数: |
13524 次 |
| 最近记录: |