gpt4 book ai didi

java - Java中使用二进制I/O分割和回传文件的机制

转载 作者:行者123 更新时间:2023-12-04 05:27:36 26 4
gpt4 key购买 nike

我遇到了连接回 .dat 文件的问题,这些文件是通过使用二进制 I/O 拆分一些文件而产生的。

某些类型的文件会出现此问题,例如 .avi 文件(不超过 2GB)。重新连接时,输出文件似乎与拆分的文件完全相同,但对于 .avi 文件,会出现“无法呈现文件”错误。 (如果您使用二进制 I/O 制作文件的副本,也会发生同样的事情)。
但是,例如,.mp4 文件已正确连接回。

我的问题是为什么会这样?因为正如我所教的 - 任何文件都只是 0 和 1 的序列。所以如果你只是重写文件的二进制序列并设置相同的文件格式 - 一切都应该正常工作。

以防万一,这是我用于拆分和连接文件的代码(它工作正常):

--- 分离器 ---

public static void main(String[] args) throws IOException {

String sourceFile = "Movie2.mp4";
int parts = 5;

BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream out;

int partSize = in.available() / parts;
byte[] b;

for (int i = 0; i < parts; i++) {
if (i == parts - 1) {
b = new byte[in.available()];
in.read(b);
out = new BufferedOutputStream(new FileOutputStream(sourceFile + "_" + i + ".dat"));
out.write(b);
out.close();
} else {
b = new byte[partSize];
in.read(b);
out = new BufferedOutputStream(new FileOutputStream(sourceFile + "_" + i + ".dat"));
out.write(b);
out.close();
}
}

in.close();
}

--- 连接器 ---
public static void main(String[] args) throws IOException {

String sourceFile;
BufferedInputStream in;
byte[] b;
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Movie2RESTORED.mp4", true));

for (int i = 0; i < 5; i++) {
sourceFile = "Movie2.mp4_" + i + ".dat";
in = new BufferedInputStream(new FileInputStream(sourceFile));
b = new byte[in.available()];
in.read(b);
out.write(b);
in.close();
}

out.close();
}

提前致谢!

最佳答案

你需要一个循环 in.read(b) .

即使 available应该返回可以在不阻塞的情况下读取的字节数,您可能需要调用 read多次获得所有这些。使用固定大小的缓冲区会更容易,但如果您坚持读取可用字节数:

int toBeRead = in.available();
byte[] b = new byte[toBeRead];
int totalRead = 0;
int read;
while ((read = in.read(b, totalRead, toBeRead-totalRead)) != -1) {
totalRead += read;
}

另外,就像aetheria提到的,你应该打电话 close关闭各种输出流。否则保存在 JVM 和 OS 缓冲区中的数据可能不会进入文件,尽管目前它们似乎这样做。

关于java - Java中使用二进制I/O分割和回传文件的机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013439/

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