Posted on 2009-03-11 11:04
morcble的blog 阅读(309)
评论(0) 编辑 收藏 所属分类:
Java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileReadAndWrite{
public static void main(String[] args) {
FileReadAndWrite fileReadAndWrite = new FileReadAndWrite();
//fileReadAndWrite.splitFile("c:/1.doc");
fileReadAndWrite.mergeFile("c:/1.doc1","c:/1.doc2");
}
public void splitFile(String filePath){
try {
FileInputStream is = new FileInputStream(filePath);
int file1Size = is.available()/2;
int buffersize = 512;
file1Size = (file1Size/buffersize)*buffersize;
//int file2Size = is.available() - file1Size;
byte buffer[] = new byte[buffersize];
int i = 0;
FileOutputStream os1 = new FileOutputStream(filePath+"1");//file 1
FileOutputStream os2 = new FileOutputStream(filePath+"2");//file 2
while ((is.read(buffer, 0, buffersize) != -1) && (buffersize > 0)) {
if((i<file1Size/buffersize)){
os1.write(buffer);
}
else{
os2.write(buffer);
}
i++;
}
os1.close();
os2.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void mergeFile(String filePath1,String filePath2){
try {
FileInputStream is1 = new FileInputStream(filePath1);
FileInputStream is2 = new FileInputStream(filePath2);
FileOutputStream os1 = new FileOutputStream(filePath1.substring(0,filePath1.length()-1));
int buffersize = 512;
byte buffer[] = new byte[buffersize];
while ((is1.read(buffer, 0, buffersize) != -1) && (buffersize > 0)) {
os1.write(buffer);
}
while ((is2.read(buffer, 0, buffersize) != -1) && (buffersize > 0)) {
os1.write(buffer);
}
is1.close();
is2.close();
os1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}