将字节数组添加到特定位置java的另一个字节数组

时间:2015-02-11 14:14:33

标签: java byte

我想创建一个大小为512字节的字节数组。

对于前100个字节,我想为文件名保留它,对于接下来的412个字节,我想用它来存储文件本身的数据。

这样的事情:

| ---- 100byte的文件名---- || ------------ 412字节的文件数据------------ |

      byte[] buffer = new byte[512];
      add the filename of  byte[] type into the first 100 position
      insert the file data after the first 100 position 

文件名可以少于100个字节。

但是我无法将文件数据附加到特定位置......我应该怎么做?

3 个答案:

答案 0 :(得分:3)

如何使用System.arraycopy()

byte[] buffer = new byte[data.length + name.length];
System.arraycopy(name, 0, buffer,           0, name.length)
System.arraycopy(data, 0, buffer, name.length, data.length)

您可能需要添加一项检查,以确保data.length + name.length不超过512。

要将名称长度固定为100,请执行以下操作:

byte[] buffer = new byte[100 + name.length];
System.arraycopy(name, 0, buffer,   0, Math.min(100, name.length))
System.arraycopy(data, 0, buffer, 100, data.length)

要将总长度固定为512,请为data.length添加限制:

byte[] buffer = new byte[512];
System.arraycopy(name, 0, buffer,   0, Math.min(100, name.length))
System.arraycopy(data, 0, buffer, 100, Math.min(412, data.length))

答案 1 :(得分:1)

您可以使用ByteBuffer。它更容易阅读和遵循其他选项。如果需要的话,你还可以获得很多其他功能。

byte[] buffer = new byte[512];
byte[] fileName = new byte[100];
byte[] data = new byte[412];

// Create a ByteBuffer from the byte[] you want to populate
ByteBuffer buf = ByteBuffer.wrap(buffer);

// Add the filename
buf.position(0);
buf.put(fileName);

// Add the file data
buf.position(99);
buf.put(data);

// Get out the newly populated byte[]
byte[] result = buf.array();

答案 2 :(得分:0)

正如@Dorus所说,

System.arraycopy适用于该名称,但文件数据可以直接读入数组:

    byte[] buffer = new byte[512];
    File file = new File("/path/to/file");
    byte[] fileNameBytes = file.getName().getBytes();
    System.arraycopy(fileNameBytes, 0, buffer, 0, fileNameBytes.length > 100 ? 100 : fileNameBytes.length);
    FileInputStream in = new FileInputStream(file); 
    in.read(buffer, 100, file.length() > 412 ? 412 : (int)file.length());
相关问题