分类
- 在try中关闭
弊端是如果文件不存在或者读取的时候有问题而抛出异常,那么就不会执行流的关闭语句,存在资源占用隐患 - 在finally中关闭
这是标准的关闭流的方式
1、首先把引用声明在try外面,使其作用域达到finally
2、在finally中先判断应用是否为空
3、再使用一次try catch进行关闭 - 使用try()关闭
把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
package JavaIOTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class SplitFileTest {
public static void main(String[] args) {
int eachReadSize = 2;
int subFileNumber;
byte[] eachContent;
File file = new File("d:/xyz/z/zzz/zzzz/lol.txt");
File dir = file.getParentFile();
if (!dir.exists()){
dir.mkdirs();
}
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try{
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStream.read(bytes);
if (0 == file.length()%eachReadSize){
subFileNumber = (int)file.length()/2;
}else{
subFileNumber = (int)file.length()/2 + 1;
}
for(int i = 0; i < subFileNumber;i++){
if(subFileNumber-1 != i){
eachContent = Arrays.copyOfRange(bytes,eachReadSize * i,(i+1) * eachReadSize);
}else {
eachContent = Arrays.copyOfRange(bytes,eachReadSize * i,(int)file.length());
}
File subFile = new File(dir+"/lol"+"-"+i+".txt");
fileOutputStream = new FileOutputStream(subFile);
fileOutputStream.write(eachContent);
fileOutputStream.close();
System.out.printf("输出子文件:%s,其大小是%d\n",subFile,subFile.length());
}
}catch (IOException e){
e.printStackTrace();
}finally {
if (fileInputStream!=null && fileOutputStream !=null ){
try {
fileOutputStream.close();
fileInputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
package JavaIOTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MergeFileText {
public static void main(String[] args) {
File targetFile = new File("d:/xyz/z/zzz/zzzz/lol3.txt");
List<File> subFiles = new ArrayList<>();
File dir = targetFile.getParentFile();
File[] allFiles = dir.listFiles();
byte[] b = new byte[2];
int len = -1;
for (File file : allFiles){
if (file.isFile()&& file.getName().startsWith("lol-")){
subFiles.add(file);
}
}
try( FileOutputStream fileOutputStream = new FileOutputStream(targetFile)){
for(File file : subFiles){
try(FileInputStream inputStream = new FileInputStream(file)) {
len = inputStream.read(b);
System.out.println(len);
}
fileOutputStream.write(b,0,len);
}
}catch (IOException e){
e.printStackTrace();
}
}
}