gpt4 book ai didi

java - 使用 Java 写入和读取文件中的多个 byte[]

转载 作者:搜寻专家 更新时间:2023-11-01 01:45:14 24 4
gpt4 key购买 nike

我必须在文件中写入字节数组。我一次做不到,所以我不能把我的阵列放在一个容器里。我的数组的大小也是可变的。其次,文件非常大,所以我必须拆分它,以便逐个数组读取它。

我该怎么做?我试着逐行写我的字节数组,但我做不到。我怎样才能在我的数组之间放置一个分隔符,然后将它拆分成这个分隔符?

编辑:

我试过这个:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(byteArray);

但是,我多次执行此代码,因此 ObjectOutputStream 每次都会添加一个损坏文件的新 header 。

我也试试:

out.write(byteArray);

但我无法分离我的数组。所以我试图附加一个'\n',但没有用。在我寻找像 FileUtils 这样的库以便逐行写入 byte[] 但我没有找到之后。

最佳答案

您可以使用现有的集合,例如List维护byte[]的List并传递

    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

关于java - 使用 Java 写入和读取文件中的多个 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com