【发布时间】:2014-06-24 17:46:23
【问题描述】:
我正在尝试与 Java 聊天。一切正常,除了特殊字符不起作用。我认为这是一个编码问题,因为在我的Outputstream 中,我将字符串编码为 UTF-8,如下所示:
protected void send(String msg) {
try {
msg+="\r\n";
OutputStream outStream = socket.getOutputStream();
outStream.write(msg.getBytes("UTF-8"));
System.out.println(msg.getBytes("UTF-8"));
outStream.flush();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
但在我的receive 方法中,我没有找到这样做的方法:
public String receive() throws IOException {
String line = "";
InputStream inStream = socket.getInputStream();
int read = inStream.read();
while (read!=10 && read > -1) {
line+=String.valueOf((char)read);
read = inStream.read();
}
if (read==-1) return null;
line+=String.valueOf((char)read);
return line;
}
那么有没有一种快速的方法来指定缓冲区读取的字节是用 UTF-8 编码的?
编辑:好的,我尝试像这样使用BufferedReader:
public String receive() throws IOException {
String line = "";
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String readLine = "";
while ((readLine = in.readLine()) != null) {
line+=readLine;
}
System.out.println("Line:"+line);
return line;
}
但它不起作用。好像socket什么都没有收到。
【问题讨论】:
标签: java sockets encoding utf-8