如何将 int 字节流转换为字符串?

发布于 2024-09-12 04:15:00 字数 218 浏览 2 评论 0原文

您好,我正在尝试在我的应用程序中实现接口 SourceStream 并覆盖方法 read(byte[],off,len) 并且我从服务器读取字节。但是我想将这些字节流转换为 String 因为我使用了string 对象 by new String(byte[]) 但它要求 off 中的初始字节和字节长度(即 len)作为参数。为什么它会这样问,因为我们只包含 Strring(bye[]) 。任何人都可以帮助我...谢谢

Hi I am trying to implement the interface SourceStream in my application and overrides the method read(byte[],off,len) and I read the bytes from a server.But I want to convert those byte stream into String for that I used a string object by new String(byte[]) but it asks the initial byte in off and length of the bytes ie len as parameters..Why it is asking like that, as we contain only Strring(bye[])only. can any one help me...Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小清晰的声音 2024-09-19 04:15:00

如果您只有一个 byte[] 那么您可以通过提供的 String(byte[],int,int) 构造函数创建一个新的 String通过API。

在你的情况下你会做

byte[] myBytes = ("Hello, World!").getBytes();
String myString = new String(myBytes, 0, myBytes.length);
System.out.println(myString);

编辑:
尝试这样的事情:

int readLength = (len > bufSize ? bufSize : len);
for (int i = 0; i < readLength; i++) {
    b[off + i] = buffers[PBuf][PByte];
}
String metaSt = new String(b, 0, readLength);

If you just have a byte[] then you can create a new String via the String(byte[],int,int) constructor provided by the API.

In your case you would do

byte[] myBytes = ("Hello, World!").getBytes();
String myString = new String(myBytes, 0, myBytes.length);
System.out.println(myString);

EDIT:
Try something like this:

int readLength = (len > bufSize ? bufSize : len);
for (int i = 0; i < readLength; i++) {
    b[off + i] = buffers[PBuf][PByte];
}
String metaSt = new String(b, 0, readLength);
神仙妹妹 2024-09-19 04:15:00

只需提供 0 作为初始偏移量和 yourArray.Length 作为长度即可。任何人都猜测为什么不提供只接受字节数组的方法 - 可能只是为了避免该方法的 101 种变体。

Just provide 0 as the initial offset and yourArray.Length as the length and you're done. Quite why a method that takes just a byte array isn't provided is anyones guess - probably just to avoid 101 variations of the method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文