2011-05-04 55 views
1

我设计使用本Java中的归档格式(只是为了好玩)模板 -如何截断java整数以适合/ exand到给定数量的字节?

First 4 bytes: Number of files in the archive 
Next 4 bytes: Number of bytes in the filename 
Next N bytes: Filename 
Next 10 bytes: Number of bytes in the file 
Next N bytes: File contents 

PHP Safe way to download mutliple files and save them

我有问题找到文件数量的值等,但我不知道如何将一个整数扩展为4个字节。

它是类似于这 - How do I truncate a java string to fit in a given number of bytes, once UTF-8 encoded?

回答

3

你可以转换一个int为4个字节是这样的:

public byte[] getBytesForInt(int value) { 
    byte[] bytes = new byte[4]; 
    bytes[0] = (byte) ((value >> 24) & 0xFF); 
    bytes[1] = (byte) ((value >> 16) & 0xFF); 
    bytes[2] = (byte) ((value >> 8) & 0xFF); 
    bytes[3] = (byte) (value & 0xFF); 
    return bytes; 
} 

这将使他们在大端顺序通常用于运输(见Endianness )。或者,如果您已经在处理OutputStream,则可以用DataOutputStream包装它,并使用writeInt()。例如按照您的模板:

FileOutputStream fileOut = new FileOutputStream("foo.dat"); 
DataOutputStream dataOut = new DataOutputStream(fileOut); 
dataOut.writeInt(numFiles); 
dataOut.writeInt(numBytesInName); 
dataOut.writeUTF(filename); 
dataOut.writeLong(numBytesInFile); 
dataOut.write(fileBytes); 

请注意,writeLong()实际上是8个字节。我不知道你为什么要使用10,我想从long 8是很多。

+0

在你的代码中,我认为第2行有错误。意外的int关键字? – liamzebedee 2011-05-04 09:36:46

+0

糟糕,错误,修复。 – WhiteFang34 2011-05-04 09:37:43

+0

我知道一个字节是8位,而java中的整数是32位。那么这意味着我甚至不需要经历所有这些,只需要写整数,因为整数是4个字节(32位) – liamzebedee 2011-05-04 09:40:50

5

使用DataOutput/DataInput实现来编写/读取该格式,它为您完成大部分工作。经典的实现是DataOutputStreamDataInputStream

DataOutputStream dos = new DataOutputStream(outputStream); 
dos.writeInt(numFiles); 
// for each file name 
byte[] fn = fileName.getBytes("UTF-8"); // or whichever encoding you chose 
dos.writeInt(fn.length); 
dos.write(fn); 
// ... 

阅读的作品几乎相同。

请注意,这些使用big endian。您必须检查(或指定)您的格式是否使用大小写。

+0

另一种选择是使用“ByteBuffer”。使用起来并不容易,但如果您希望在不复制的情况下对数据的某些部分进行多次传递,那就太好了。 – 2011-05-04 09:45:52

+0

@Daniel:的确如此。 ['ByteBuffer'](http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html)也具有[可配置的字节顺序/字节顺序](http:// download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html#order(java.nio.ByteOrder))。 – 2011-05-04 09:55:32