以1024字节的块分割Java String [英] Split Java String in chunks of 1024 bytes

查看:523
本文介绍了以1024字节的块分割Java String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中将字符串拆分为1024字节的块的有效方法是什么?
如果有多个块,则需要在所有后续块中重复标题(固定大小的字符串)。

What's an efficient way of splitting a String into chunks of 1024 bytes in java? If there is more than one chunk then the header(fixed size string) needs to be repeated in all subsequent chunks.

推荐答案

字符串和字节是两个完全不同的东西,所以想要将一个字符串拆分成字节就像想要将一个绘画分成几个节目一样毫无意义。

Strings and bytes are two completely different things, so wanting to split a String into bytes is as meaningless as wanting to split a painting into verses.

它是什么你真的想做什么?

What is it that you actually want to do?

要在字符串和字节之间进行转换,你需要指定一个可以编码String中所有字符的编码。根据编码和字符,它们中的一些可能跨越多个字节。

To convert between strings and bytes, you need to specify an encoding that can encode all the characters in the String. Depending on the encoding and the characters, some of them may span more than one byte.

您可以将字符串拆分为1024个字符的块并将其编码为字节,但是每个块可能超过1024个字节。

You can either split the String into chunks of 1024 characters and encode those as bytes, but then each chunk may be more than 1024 bytes.

或者你可以将原始字符串编码为字节,然后将它们分成1024个块,但是你必须确保将它们作为字节附加,然后将整个字符串解码为再次使用String,或者当一个字符超过1个字节时,你可能会在分裂点处出现乱码。

Or you can encode the original string into bytes and then split them into chunks of 1024, but then you have to make sure to append them as bytes before decoding the whole into a String again, or you may get garbled characters at the split points when a character spans more than 1 byte.

如果你担心String可以使用内存很长一段时间,你应该使用流(java.io包)来进行en / decode和splitting,以避免数据作为副本多次保存在内存中。理想情况下,您应该避免将原始字符串整合在一起,而是使用流从任何地方以小块的形式读取它。

If you're worried about memory usage when the String can be very long, you should use streams (java.io package) to to the en/decoding and splitting, in order to avoid keeping the data in memory several times as copies. Ideally, you should avoid having the original String in one piece at all and instead use streams to read it in small chunks from wherever you get it from.

这篇关于以1024字节的块分割Java String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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