【问题标题】:change all new line separators to crlf from cr or crlf on bytes在字节上将所有新行分隔符从 cr 或 crlf 更改为 crlf
【发布时间】:2013-07-24 12:59:58
【问题描述】:

我需要将所有新行分隔符更改为 \r\n。在字节表中有一些 \r 和一些 \r\n

byte[] data = (byte[]) transformedToByteObject;

数据包含该字节,但我不知道如何处理该更改,我只需要处理字节和字节,无法转换为字符串

【问题讨论】:

    标签: java byte bytearray newline


    【解决方案1】:

    首先,您需要了解换行符只是相对于特定字符编码的换行符。幸运的是,几乎每个字符编码都在底端使用相同的 ASCII 集,\n 和 \r 是其中的一部分。

    有多种方法可以解决这个问题,效率和复杂程度各不相同。采用低效率但低复杂度的方法:

    遍历transformedToByteObject 数组,如果字符不是(byte) '\r',则将其复制到目标数组。

    如果是'\r',那么你也将它复制到你的目标数组,但是检查下一个字符是否是'\n'。如果不是,则在目标数组中插入一个。

    一些提示:您的目标数组最多是您的输入数组的 2 倍(最坏的情况,您的输入数组只是充满了'\r')。因此,您可以使用transformedToByteObject.length * 2 初始化您的目的地。记录实际写入的字节数,一旦知道转换后的长度,使用System.arrayCopy()将这些字节复制到另一个精确大小的字节数组中

    一个这样的实现可能如下所示:

    final byte[] original = ...;
    final byte[] transformed = new byte[original.length * 2];
    int len = 0;
    
    for (int i = 0; i < original.length; i++) // for each original byte ...
    {
      transformed[len] = original[i];         // copy the byte
      len++;                                  // track the number of transformed bytes written
    
      if (original[i] == (byte) '\r')         // if this is a \r ...
      {
        if (i + 1 < original.length &&        // ... and there is a character that follows ...
            original[i+1] != (byte) '\n')     // ... and that character is not a \n ...
        {
          transformed[len] = (byte) '\n';     // ... insert a \n
          len++;                              // ... being sure to track the number of bytes written
        }
      }
    }
    
    final byte[] result = new byte[len];              // prepare an exact sized array
    System.arrayCopy(transformed, 0, result, 0, len); // and copy the transformed bytes into it
    

    【讨论】:

    • 糟糕 - 我的代码有一个错误,如果最后一个字符是 '\r',我们不会将其更改为 '\r\n'。我会把它作为练习留给读者...... ;-)
    猜你喜欢
    • 1970-01-01
    • 2010-09-06
    • 2018-06-20
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多