用于字节数组操作的Java库?

时间:2012-05-24 14:25:39

标签: java bytearray

是否有可用的免费库包含操作字节数组的常用方法?

它应该能够至少执行以下操作至少ob字节数组,但其他数组类型也会很好:

  • 搜索子阵列
  • 搜索并替换
  • 在特定位置插入元素
  • 删除某个位置的子阵列

我知道所有这些功能并不是很高级的魔法,但是完全实现它们是愚蠢的。包括相应单元测试在内的错误证明需要一些时间。

因此,我正在搜索包含这些功能的(非GPL)库。 有人知道这样的图书馆吗?

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:-1)

我认为您的前三个问题可以通过 Java.util.Arrays 类来解决,您不需要第三方库。

Arrays.binarySearch() method is for your first problem.
Arrays.fill() method for your second problem.

对于上一个问题,我可以推荐一些我知道的第三方工具包。

Google的Guava,Apache的commons API可能有所帮助。

答案 2 :(得分:-1)

我猜你可以把阵列变成Collection来做你需要的。如果您不想使用Collections,并且只处理byte[],则可以执行以下操作:

public class A {

    public static byte[] deleteSubarray(byte[] array, byte[] subArray) {
        int p = searchFor(array, subArray);
        if (p == -1)
            return array;
        byte[] result = new byte[array.length - subArray.length + 1];
        for (int i = 0; i < p; i++)
            result[i] = array[i];
        for (int i = p + subArray.length - 1; i < array.length; i++) {
            result[p] = array[i];
            p++;
        }
        return result;
    }

    public static byte[] insertElementAt(byte[] array, byte element, int position) {
        byte[] result = new byte[array.length + 1];
        for (int i = 0; i <= position - 1; i++)
            result[i] = array[i];
        result[position] = element;
        for (int i = position + 1; i < array.length; i++) {
            result[i] = array[i];
        }
        return result;
    }

    public static byte[] searchAndReplace(byte[] array, byte[] search, byte[] replace) {
        if (search.length != replace.length)
            return array;
        int p = searchFor(array, search);
        if (p == -1)
            return array;
        byte[] result = Arrays.copyOf(array, array.length);
        for (int i = 0; i < replace.length; i++) {
            result[p] = replace[i];
            p++;
        }
        return result;
    }

    public static int searchFor(byte[] array, byte[] subArray) {
        if (subArray.length > array.length)
            return -1;
        int p = (new String(array)).indexOf(new String(subArray));
        for (int i = 1; i < subArray.length; i++) {
            if (array[p + i] != subArray[i])
                return -1;
        }
        return p;
    }

    public static void main(String[] args) {
        String a = "hello world!";
        String b = "lo w";
        System.out.println(searchFor(a.getBytes(), b.getBytes()));
        System.out.println(new String(searchAndReplace(a.getBytes(), b.getBytes(), "mn x".getBytes())));
        System.out.println(new String(insertElementAt(a.getBytes(), "-".getBytes()[0], 5)));
        System.out.println(new String(deleteSubarray(a.getBytes(), b.getBytes())));
    }

}

输出:

3
helmn xorld!
hello-world!
helworld!

如果您还处理其他类型的数组,那么searchFor不起作用,但您可以轻松地概括:)