当前位置: 技术问答>java相关
怎么能接收通过socket传来的中文数据呢?我如果用BufferReader的话socket连接就无效了
来源: 互联网 发布时间:2015-07-02
本文导语: 怎么能接收通过socket传来的中文数据呢?我如果用BufferReader的话socket连接就无效了 | 比如你要发送String str = "测试";字段,如果你能保证发送前字符编码是正确的,不会乱码,那么接收到的自然就是正确...
怎么能接收通过socket传来的中文数据呢?我如果用BufferReader的话socket连接就无效了
|
比如你要发送String str = "测试";字段,如果你能保证发送前字符编码是正确的,不会乱码,那么接收到的自然就是正确的了。
如果发送前就为乱码
可以先转一下:(类似以下处理)
str=new String (str.getBytes("ISO-8859-1"),"gb2312");
其实如果只是发送简单的中文字串,直接使用print或者readLine方法发送和接收倒也不会有什么大问题,但要顾及到很多细节的化,最好打包成byte[]数组发送为好,接收到再转为String
使用DateInputStream和DateOutputStream的write方法和read方法发送和接收
当然打包解包又会复杂一些
如果发送前就为乱码
可以先转一下:(类似以下处理)
str=new String (str.getBytes("ISO-8859-1"),"gb2312");
其实如果只是发送简单的中文字串,直接使用print或者readLine方法发送和接收倒也不会有什么大问题,但要顾及到很多细节的化,最好打包成byte[]数组发送为好,接收到再转为String
使用DateInputStream和DateOutputStream的write方法和read方法发送和接收
当然打包解包又会复杂一些
|
faint
BufferedReader是用来读取文本文件流的,
仔细看看它的api文档阿
Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example, BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
BufferedReader是用来读取文本文件流的,
仔细看看它的api文档阿
Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example, BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
|
读取时加上字符编码
|
到底是什么问题 说清楚点
|
当然可以,不管是英文也好中文也好或是其他数据,最终传输的都是一样的,都是二进制流,你可以根据二进制流构造字符串,就可以得到中文了。