gpt4 book ai didi

java - Java 中的文件分割代码未按要求工作

转载 作者:行者123 更新时间:2023-12-02 10:30:40 26 4
gpt4 key购买 nike

我尝试了以下文件分割代码,它可以工作,但不符合要求。即,一个名为“song.mp3”的 mp3 文件大小为 2540KB,预期 block 数(每个 100KB)为 25,但代码仅给出 12 个 block ,我不明白原因。

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

File file = new File("song.mp3");

FileInputStream fIn = new FileInputStream("song.mp3");
FileOutputStream fOut = new FileOutputStream("song_0.mp3");
int chunk_size = 1024 * 100;
byte[] buff = new byte[chunk_size]; // 100KB file
int i = 0;
String file_name = file.getName();
String file_name_base = file_name.substring(0,
file_name.lastIndexOf("."));
while (fIn.read() != -1) {

fIn.read(buff);
int total_read = 0;
total_read += chunk_size;
long read_next_chunk = total_read;
String file_name_new = file_name_base + "_" + i + ".mp3";
File file_new = new File(file_name_base);
i++;
fOut = new FileOutputStream(file_name_new);
fOut.write(buff);

fIn.skip(total_read);// skip the total read part

} // end of while loop

fIn.close();
fOut.close();

}

最佳答案

您的代码肯定不起作用,至少是因为:
在每次迭代中,您都会读取 1 个字节,并通过 while (fIn.read() != -1) 将其丢弃。
将循环更改为如下所示:

int bytesReadCounter;
while((bytesReadCounter = fIn.read(buff, 0, chunk_size)) > 0){
..................................
fOut.write(buff, 0, bytesReadCounter);
..................................
}

buff 中存储读取的字节数,在 bytesReadCounter 中存储读取的字节数。
然后,您从 buff 写入 fOut,恰好是 bytesReadCounter 字节。

编辑,使用此代码:

public static void main(String[] args) {
File file = new File("song.mp3");

FileInputStream fIn = null;
try {
fIn = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

int chunk_size = 1024 * 100;
byte[] buff = new byte[chunk_size]; // 100KB file
int i = 0;
String file_name = file.getName();
String file_name_base = file_name.substring(0, file_name.lastIndexOf("."));
int bytesReadCounter;
boolean hasMore = true;
while (hasMore) {
try {
bytesReadCounter = fIn.read(buff, 0, chunk_size);
} catch (IOException e) {
e.printStackTrace();
break;
}

hasMore = bytesReadCounter > 0;

if (!hasMore)
break;

String file_name_new = file_name_base + "_" + i + ".mp3";
File file_new = new File(file_name_new);

FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file_new);
} catch (FileNotFoundException e) {
e.printStackTrace();
break;
}

try {
fOut.write(buff, 0, bytesReadCounter);
fOut.close();
} catch (IOException e) {
e.printStackTrace();
break;
}

i++;
}

try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}

关于java - Java 中的文件分割代码未按要求工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53631076/

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