package com.Lucky.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
io异常的处理方法:
*/
public class ioTryCatch {
public static void main(String[] args) throws IOException {
System.out.println("----- //初级使用try catch-------");
FileInputStream inputTry=null; //必须先赋值为null
FileOutputStream outTry=null;
try {
//创建
inputTry=new FileInputStream("H:\\项目\\javaSE\\IO\\src\\com\\Lucky\\io\\test.txt"); //读取对象
outTry=new FileOutputStream("H:\\项目\\javaSE\\IO\\src\\com\\Lucky\\io\\copymaxData.txt"); //输出对象
//创建一次读取的字节数组
byte[] arrTry=new byte[5]; //数组长度为5
//遍历
int valTry; //每一次遍历几个字节
while ((valTry=inputTry.read(arrTry))!=-1){ //读取
//输出到copy文件中【参数1:要写的数据源;参数2:开始索引;参数3:个数】
outTry.write(arrTry,0,valTry);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源{先开后关} --》可以保证数据读取完整
//判断outTry对象是否是null
if(outTry!=null){
try {//因为close可能也存在异常
outTry.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//判断inputTry对象是否是null
if(outTry!=null){
try {//因为close可能也存在异常
inputTry.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println();
System.out.println("----- //中级级使用try catch【jdk7的写法】-------");
try (FileInputStream iTry=new FileInputStream("H:\\项目\\javaSE\\IO\\src\\com\\Lucky\\io\\test.txt"); //读取对象
FileOutputStream oTry=new FileOutputStream("H:\\项目\\javaSE\\IO\\src\\com\\Lucky\\io\\copymaxData.txt"); ){
//创建一次读取的字节数组
byte[] arrTry=new byte[5]; //数组长度为5
//遍历
int valTry; //每一次遍历几个字节
while ((valTry=iTry.read(arrTry))!=-1){ //读取
//输出到copy文件中【参数1:要写的数据源;参数2:开始索引;参数3:个数】
oTry.write(arrTry,0,valTry);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
////////////////////////////////////////////////////////////////////////////////////////
System.out.println();
System.out.println("----- //中级级使用try catch【jdk9的写法】-------");
FileInputStream fis=new FileInputStream("H:\\项目\\javaSE\\IO\\src\\com\\Lucky\\io\\test.txt");
FileOutputStream fos=new FileOutputStream("H:\\项目\\javaSE\\IO\\src\\com\\Lucky\\io\\copymaxData.txt");
try (fis;fos){
//创建一次读取的字节数组
byte[] arrTry=new byte[5]; //数组长度为5
//遍历
int valTry; //每一次遍历几个字节
while ((valTry=fis.read(arrTry))!=-1){ //读取
//输出到copy文件中【参数1:要写的数据源;参数2:开始索引;参数3:个数】
fos.write(arrTry,0,valTry);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}