我正在尝试将一个二进制文件(如视频/音频/图像)分成每个100kb的块,然后将这些块连接起来,以获得原始文件。我的代码似乎正常工作,从某种意义上说,它分割文件并加入块,我得到的文件与原始文件的大小相同。然而,问题是内容被截断了-也就是说,如果它是一个视频文件,它会在2秒后停止,如果它是图像文件,那么只有上半部分看起来是正确的。
下面是我使用的代码(如果你愿意,我可以发布完整的代码):
对于除法:
File ifile = new File(fname);
FileInputStream fis;
String newName;
FileOutputStream chunk;
int fileSize = (int) ifile.length();
int nChunks = 0, read = 0, readLength = Chunk_Size;
byte[] byteChunk;
try {
fis = new FileInputStream(ifile);
StupidTest.size = (int)ifile.length();
while (fileSize > 0) {
if (fileSize <= Chunk_Size) {
readLength = fileSize;
}
byteChunk = new byte[readLength];
read = fis.read(byteChunk, 0, readLength);
fileSize -= read;
assert(read==byteChunk.length);
nChunks++;
newName = fname + ".part" + Integer.toString(nChunks - 1);
chunk = new FileOutputStream(new File(newName));
chunk.write(byteChunk);
chunk.flush();
chunk.close();
byteChunk = null;
chunk = null;
}
fis.close();
fis = null;
对于连接文件,我将所有块的名称放在一个列表中,然后按名称对其进行排序,然后运行以下代码:
File ofile = new File(fname);
FileOutputStream fos;
FileInputStream fis;
byte[] fileBytes;
int bytesRead = 0;
try {
fos = new FileOutputStream(ofile,true);
for (File file : files) {
fis = new FileInputStream(file);
fileBytes = new byte[(int) file.length()];
bytesRead = fis.read(fileBytes, 0,(int) file.length());
assert(bytesRead == fileBytes.length);
assert(bytesRead == (int) file.length());
fos.write(fileBytes);
fos.flush();
fileBytes = null;
fis.close();
fis = null;
}
fos.close();
fos = null;
发布于 2010-12-14 02:16:03
我只能在代码中发现两个潜在的错误:
int fileSize = (int) ifile.length();
当文件超过2 2GB时,上述操作将失败,因为int
不能容纳更多。
newName = fname + ".part" + Integer.toString(nChunks - 1);
这样构造的文件名应该以一种非常具体的方式排序。当使用默认字符串排序时,name.part10
将排在name.part2
之前。您希望提供一个定制的Comparator
,它提取并解析作为整数的零件号,然后按整数进行比较。
发布于 2010-12-14 02:20:16
有超过10个块吗?然后程序将连接*.part1 + *.part10 + *.part2,依此类推。
发布于 2012-08-28 03:26:28
用于拆分文件:->
import java.io.*;
class Split
{
public static void main(String args[])throws IOException
{
Console con=System.console();
System.out.println("enter the file name");
String path=con.readLine();
File f= new File(path);
int filesize=(int)f.length();
FileInputStream fis= new FileInputStream(path);
int size;
System.out.println("enter file size for split");
size=Integer.parseInt(con.readLine());
byte b[]=new byte[size];
int ch,c=0;
while(filesize>0)
{
ch=fis.read(b,0,size);
filesize = filesize-ch;
String fname=c+"."+f.getName()+"";
c++;
FileOutputStream fos= new FileOutputStream(new File(fname));
fos.write(b,0,ch);
fos.flush();
fos.close();
}
fis.close();
}
}
https://stackoverflow.com/questions/4431945
复制相似问题