java IO流笔记 IO流异常处理
JDK7之前IO流这样处理:
public class Test {
public static void main(String[] args) {
/**
* jdk7之前的标准io异常处理
*/
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("IO流\\aaa\\1.txt");
fileOutputStream = new FileOutputStream("IO流\\aaa\\1_copy.txt");
byte[] b = new byte[8192];
int len = 0;
while ((len = fileInputStream.read(b))!=-1){
fileOutputStream.write(b,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileOutputStream!=null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileInputStream!=null){
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/** * jdk7开始 * try-with-resoure语句,该语句保证了每个资源在语句结束是关闭资源 */
public class Test2 {
public static void main(String[] args) {
/**
* jdk7开始
* try-with-resoure语句,该语句保证了每个资源在语句结束是关闭资源
*/
try (
//把创建流的代码放在()小括号里面
FileInputStream fileInputStream = new FileInputStream("IO流\\aaa\\2.txt");
FileOutputStream fileOutputStream = new FileOutputStream("IO流\\aaa\\2_copy.txt");
){
byte[] b = new byte[8192];
int len = 0;
while ((len = fileInputStream.read(b))!=-1){
fileOutputStream.write(b,0,len);
}
//这段代码不用写了
/* fileOutputStream.close();
fileInputStream.close();*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上两种方式都可以,自己看着来使用