使用DataOutputStream编写大字符串 [英] Writing large strings with DataOutputStream

查看:205
本文介绍了使用DataOutputStream编写大字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些套接字编程,以便通过网络传输信息。我遇到了DataOutputStream.writeUTF()的问题。它似乎允许高达64k的字符串,但我有一些情况,我可以跑过这个。有没有什么好的替代品支持更大的字符串或者我需要自己滚动?

I've been doing some socket programming to transmit information across the wire. I've run into a problem with DataOutputStream.writeUTF(). It seems to allow strings of up to 64k but I have a few situations where I can run over this. Are there any good alternatives that support larger strings or do I need to roll my own?

推荐答案

它实际上使用两个字节来在使用将其压缩为每个字符一个,两个或三个字节的算法之前写入字符串的长度。 (请参阅有关java.io.DataOutput的文档)它接近于UTF-8,但即使记录为如此,也存在兼容性问题。如果您不是非常担心要编写的数据量,可以先编写字符串的长度,然后使用getBytes方法写入字符串的原始数据,轻松编写自己的数据。

It actually uses a two bytes to write the length of the string before using an algorithm that compacts it into one, two or three bytes per character. (See the documentation on java.io.DataOutput) It is close to UTF-8, but even though documented as being so, there are compatibility problems. If you are not terribly worried about the amount of data you will be writing, you can easily write your own by writing the length of the string first, and then the raw data of the string using the getBytes method.

// Write data
String str="foo";
byte[] data=str.getBytes("UTF-8");
out.writeInt(data.length);
out.write(data);

// Read data
int length=in.readInt();
byte[] data=new byte[length];
in.readFully(data);
String str=new String(data,"UTF-8");

这篇关于使用DataOutputStream编写大字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆