【问题标题】:Java: Remove first UTF string from byte arrayJava:从字节数组中删除第一个 UTF 字符串
【发布时间】:2014-04-25 18:00:30
【问题描述】:

我正在尝试从字节数组中删除写入的字符串并保留原​​始的单独对象:

byte[] data... // this is populated with the following:
// 00094E6966747943686174001C00074D657373616765000B4372616674656446757279000474657374
// to string using converter : "    ChannelMessageUsernametest"
// notice that tab/whitespace, ignore quotes
// The byte array was compiled by writing the following (writeUTF from a writer):
// Channel
// Message
// Username
// test

现在我正在尝试从字节数组中删除 Channel

ByteArrayDataInput input = ByteStreams.newDataInput(message);
String channel = input.readUTF(); // Channel, don't want this
String message = input.readUTF(); // Message
// works good, but I don't want Channel,
// and I can't remove it from the data before it arrives,
// I have to work with what I have

这是我的问题:

byte[] newData = Arrays.copyOfRange(data, channel.length() + 2, data.length)
// I use Arrays.copyOfRange to strip the whitespace (I assume it's not needed)
// As well, since it's inclusive of length size, I have to add 1 more,
// resulting in channel.length() + 1
// ...
ByteArrayDataInput newInput = ByteStreams.newDataInput(message);
String channel = newInput.readUTF(); // MessageUsernametext

看看我如何失去对象的分离,如何将原始byte[] data中的对象的原始“部分”保留在byte[] newData中。

  • 可以安全地假设String channel(剥离前后)是一个字符串
  • 假设每个对象都是一个字符串是不安全的,假设一切都是随机的,因为它是

【问题讨论】:

    标签: java bytearrayinputstream arrays


    【解决方案1】:

    只要您能保证channel 始终在合理的字符范围内(例如字母数字),将channel.length() + 2 更改为channel.length() + 4 就足够了。

    【讨论】:

      【解决方案2】:

      Java 字符串具有 16 位元素,因此将字节数组转换为字符串是安全的,尽管内存效率不高:

      private byte[] removeElements(byte[] data, int fromIndex, int len) {
             String str1 = new String(data).substring(0,fromIndex);
             String str2 = new String(data).substring(fromIndex+len,data.length);
             return (str1+str2).getBytes();
      }
      

      同样的方法,你也可以在字节数组中搜索一个String:

      private int findStringInByteArray(byte[] mainByte, String str, int fromIndex) {
          String main = new String(mainByte);
          return main.indexOf(str,fromIndex);
      }
      

      现在您可以一起调用这些方法:

      byte[] newData = removeElements(
          data,
          findStringInByteArray(data,channel,0),
          channel.length() );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-29
        • 2013-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多