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