11.练习_文件拆分和合并
学习:第7遍
1.练习:文件拆分和合并 将"c:/aaa/src.zip"20M大小的文件拆分成每6M为一个小文件 src.zip_1 src.zip_2 src.zip_3 src.zip_4
public class TestStream {
public static void main(String
[] args
) {
String filePath
="c:/aaa/src.zip";
splitFile(filePath
);
mergeFile(filePath
+"_2");
}
public static void splitFile(String filePath
) {
FileInputStream fis
= null
;
FileOutputStream fos
= null
;
try {
fis
= new FileInputStream(filePath
);
byte[] buffer
= new byte[1024 * 1024 * 6];
int num
= -1;
int index
= 0;
while ((num
= fis
.read(buffer
)) != -1) {
fos
= new FileOutputStream(filePath
+ "_" + (++index
));
fos
.write(buffer
, 0, num
);
fos
.flush();
fos
.close();
}
System
.out
.println("拆分成功,共拆分为:" + index
+ "个");
} catch (FileNotFoundException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
} finally {
if (fis
!= null
) {
try {
fis
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
public static void mergeFile(String filePath
) {
String basePath
= filePath
.substring(0, filePath
.lastIndexOf("_"));
FileOutputStream fos
= null
;
FileInputStream fis
= null
;
try {
fos
= new FileOutputStream(basePath
);
int index
= 1;
File file
= null
;
while ((file
= new File(basePath
+ "_" + index
++)).exists()) {
fis
= new FileInputStream(file
);
byte[] buffer
= new byte[fis
.available()];
fis
.read(buffer
);
fos
.write(buffer
);
fos
.flush();
fis
.close();
}
System
.out
.println("合并成功:"+basePath
);
} catch (FileNotFoundException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
} finally {
if (fos
!= null
) {
try {
fos
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-24885.html