如何截断java整数以适合/ exand到给定的字节数?

lia*_*dee 1 java int byte archive

我正在使用这个模板设计一个Java格式的存档格式(只是为了好玩) -

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
Run Code Online (Sandbox Code Playgroud)

PHP安全的方式下载多个文件并保存.

我在查找文件数量等方面遇到了麻烦,但我不知道如何将整数扩展为4个字节.

它是否与此类似- 一旦UTF-8编码,如何截断一个java字符串以适应给定的字节数?

Joa*_*uer 5

使用DataOutput/ DataInputimplementation来编写/读取该格式,它可以为您完成大部分工作.经典的实现是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);
// ...
Run Code Online (Sandbox Code Playgroud)

阅读的作用几乎相同.

请注意,这些使用大端.您必须检查(或指定)您的格式是使用大端还是小端.