您可以使用现有的集合,例如 List 来维护 byte[] 的列表并传输它
List<byte[]> list = new ArrayList<byte[]>();
list.add("HI".getBytes());
list.add("BYE".getBytes());
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
"test.txt"));
out.writeObject(list);
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"test.txt"));
List<byte[]> byteList = (List<byte[]>) in.readObject();
//if you want to add to list you will need to add to byteList and write it again
for (byte[] bytes : byteList) {
System.out.println(new String(bytes));
}
输出:
HI
BYE
另一种选择是使用RandomAccessFile。这不会强迫您阅读完整的文件,您可以跳过不想阅读的数据。
DataOutputStream dataOutStream = new DataOutputStream(
new FileOutputStream("test1"));
int numberOfChunks = 2;
dataOutStream.writeInt(numberOfChunks);// Write number of chunks first
byte[] firstChunk = "HI".getBytes();
dataOutStream.writeInt(firstChunk.length);//Write length of array a small custom protocol
dataOutStream.write(firstChunk);//Write byte array
byte[] secondChunk = "BYE".getBytes();
dataOutStream.writeInt(secondChunk.length);//Write length of array
dataOutStream.write(secondChunk);//Write byte array
RandomAccessFile randomAccessFile = new RandomAccessFile("test1", "r");
int chunksRead = randomAccessFile.readInt();
for (int i = 0; i < chunksRead; i++) {
int size = randomAccessFile.readInt();
if (i == 1)// means we only want to read last chunk
{
byte[] bytes = new byte[size];
randomAccessFile.read(bytes, 0, bytes.length);
System.out.println(new String(bytes));
}
randomAccessFile.seek(4+(i+1)*size+4*(i+1));//From start so 4 int + i* size+ 4* i ie. size of i
}
输出:
BYE