繁体   English   中英

如何用Java将字符串切成1兆字节的subString?

[英]How to cut a String into 1 megabyte subString with Java?

我想出了以下几点:

public static void cutString(String s) {
    List<String> strings = new ArrayList<>();
    int index = 0;
    while (index < s.length()) {
        strings.add(s.substring(index, Math.min(index + 1048576, s.length())));
        index += 1048576;
    }
}

但是我的问题是,使用UTF-8某些字符并不能完全占用1个字节,因此使用1048576告诉在哪里剪切字符串是行不通的。 我正在考虑也许使用Iterator,但这似乎并不高效。 最有效的解决方案是什么? 为了避免字符切片,字符串可以小于1 Mb,但不能大于!

快速,不安全的骇客

您可以使用s.getBytes("UTF-8")获得一个数组,其中包含每个UTF-8字符使用的实际字节。 像这样:

System.out.println("¡Adiós!".getBytes("UTF-8").length);
// Prints: 9

一旦有了,只需将字节数组拆分为长度为1048576的块,然后使用new String(chunk, "UTF-8")将这些块重新转换为UTF-8字符串。

但是,通过这样做, 您可以在块的开头或结尾处中断多字节字符 假设第1048576个字符是一个3字节的Unicode字符:第一个字节将进入第一个块,其他两个字节将进入第二个块,从而破坏编码。

正确的方法

如果您可以放宽对“ 1 MB”的要求,则可以采用一种更安全的方法:将字符串分成1048576个字符(不是字节)的块,然后使用getBytes测试每个块的实际长度,并根据需要从末尾删除字符,直到实际大小等于或小于1 MB。

这是一个不会破坏字符的实现,但要牺牲一些行小于给定大小的行:

public static List<String> cutString(String original, int chunkSize, String encoding) throws UnsupportedEncodingException {
    List<String> strings = new ArrayList<>();
    final int end = original.length();
    int from = 0, to = 0;
    do {
        to = (to + chunkSize > end) ? end : to + chunkSize; // next chunk, watch out for small strings
        String chunk = original.substring(from, to); // get chunk
        while (chunk.getBytes(encoding).length > chunkSize) { // adjust chunk to proper byte size if necessary
            chunk = original.substring(from, --to);
        }
        strings.add(chunk); // add chunk to collection
        from = to; // next chunk
    } while (to < end);
    return strings;
}

我用chunkSize = 24对其进行了测试,以便可以看到效果。 它应该与任何其他大小一起工作:

    String test = "En la fase de maquetación de un documento o una página web o para probar un tipo de letra es necesario visualizar el aspecto del diseño. ٩(-̮̮̃-̃)۶ ٩(●̮̮̃•̃)۶ ٩(͡๏̯͡๏)۶ ٩(-̮̮̃•̃).";

    for (String chunk : cutString(test, 24, "UTF-8")) {
        System.out.println(String.format(
                "Chunk [%s] - Chars: %d - Bytes: %d",
                chunk, chunk.length(), chunk.getBytes("UTF-8").length));
    }
    /*
    Prints:
        Chunk [En la fase de maquetaci] - Chars: 23 - Bytes: 23
        Chunk [ón de un documento o un] - Chars: 23 - Bytes: 24
        Chunk [a página web o para pro] - Chars: 23 - Bytes: 24
        Chunk [bar un tipo de letra es ] - Chars: 24 - Bytes: 24
        Chunk [necesario visualizar el ] - Chars: 24 - Bytes: 24
        Chunk [aspecto del diseño. ٩(] - Chars: 22 - Bytes: 24
        Chunk [-̮̮̃-̃)۶ ٩(●̮̮] - Chars: 14 - Bytes: 24
        Chunk [̃•̃)۶ ٩(͡๏̯͡] - Chars: 12 - Bytes: 23
        Chunk [๏)۶ ٩(-̮̮̃•̃).] - Chars: 14 - Bytes: 24
     */

另一个测试使用3 MB的字符串,例如您在评论中提到的字符串:

    String string = "0123456789ABCDEF";
    StringBuilder bigAssString = new StringBuilder(1024*1024*3);
    for (int i = 0; i < ((1024*1024*3)/16); i++) {
        bigAssString.append(string);
    }
    System.out.println("bigAssString.length = " + bigAssString.toString().length());
    bigAssString.replace((1024*1024*3)/4, ((1024*1024*3)/4)+1, "á");

    for (String chunk : cutString(bigAssString.toString(), 1024*1024, "UTF-8")) {
        System.out.println(String.format(
                "Chunk [...] - Chars: %d - Bytes: %d",
                chunk.length(), chunk.getBytes("UTF-8").length));
    }
    /*
    Prints:
        bigAssString.length = 3145728
        Chunk [...] - Chars: 1048575 - Bytes: 1048576
        Chunk [...] - Chars: 1048576 - Bytes: 1048576
        Chunk [...] - Chars: 1048576 - Bytes: 1048576
        Chunk [...] - Chars: 1 - Bytes: 1
     */

您可以将ByteArrayOutputStream与OutputStreamWriter一起使用

   ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer w = OutputStreamWriter(out, "utf-8");
    //write everything to the writer
    w.write(myString);
    byte[] bytes = out.toByteArray();
    //now you have the actual size of the string, you can parcel by Mb. Be aware that problems may occur however if you have a multi-byte character separated into two locations

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM