合并一个文件夹下的n个小文件,合并后的大文件最大10MB,超出后继续合并其余小文件到,还是最大10MB,以此类推。
麻烦帮我看看那儿错了,我只能限制第一个大文件10MB,后面的就不行了!
多谢!
import java.io.*;
public class FilesIn {
public static void main(String[] args) {
File dir = new File("E://testdata");
File out=new File("E://Separator");
try {
SaveFile(dir,out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void SaveFile(File dir, File dst) throws IOException {
String[] children = dir.list();
FilenameFilter filter = new FilenameFilter(){
public boolean accept(File dir, String name) {
return true;
}
};
File filePath = new File("E://Separator");
String fileIndex="0";
File FileBig = new File(filePath + "/" + "Files"+"_"+fileIndex);
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(FileBig));
children = dir.list(filter);
for (int i = 0; i < children.length; i++){
String inhalt = children[i];
FileInputStream in=new FileInputStream(dir+"/" + inhalt);
byte[] buffer = new byte[1024];
int len;
if(FileBig.length()/1024/1024<10){
while ( (len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
} //out.close();
}
else
{
int fileIndexInt = Integer.parseInt(fileIndex)+1;
File FileBig1 = new File(filePath + "/" + "Files"+"_"+fileIndexInt);
BufferedOutputStream out1=new BufferedOutputStream(new FileOutputStream(FileBig1));
while ( (len = in.read(buffer)) > 0) {
out1.write(buffer, 0, len);
out.close();
}out1.close();
fileIndex = String.valueOf(fileIndexInt);
}
}
out.close();
}
}
应该把 else里的 File FileBig1 改成 FileBig,具体把我写的for替换掉你的for就应该可以实现了。
for (int i = 0; i < children.length; i++) {
String inhalt = children[i];
FileInputStream in = new FileInputStream(dir + "/" + inhalt);
byte[] buffer = new byte[1024];
int len=0;
if (FileBig.length() / 1024 / 1024 < 10) {
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();// out.close();
} else {
int fileIndexInt = Integer.parseInt(fileIndex) + 1;
FileBig = new File(filePath + "/" + "Files" + "_"
+ fileIndexInt);
out = new BufferedOutputStream(
new FileOutputStream(FileBig));
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
//out.close();
fileIndex = String.valueOf(fileIndexInt);
}
}code]
[code="java"]
final int MAX_LENGTH = 10 * 1024 * 1024;
//...
for (int i = 0; i /*小於*/ children.length; i++) {
if (fileBig.length() >= MAX_LENGTH) {
fileBig.close();
fileIndex++;
fileBig = new File(filePath + File.separator + "FILE" + fileIndex);
// FileOutputStream out = new .....
}
// read and write
out.flush();
}
[/code]
问题就是你都把File [color=red]FileBig [/color]= new File(filePath + "/" + "Files"+"_"+fileIndex);
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(FileBig));
filebig定义在循环的外面,写完第一个大文件后,你又不新建一个新的大文件