0
点赞
收藏
分享

微信扫一扫

Java中 IO流异常处理的方式


Java中 IO流异常处理的方式

1. 消极处理异常

// 1. 消极处理异常
public static void main(String[] args)throws
IOException {
FileOutputStream fos = new
FileOutputStream("file/test.txt");
FileInputStream fis = new
FileInputStream("file/test.txt");
String str = "helloworld";
// 文件字节输出流
for(int i=0;i<str.length();i++) {
char c = str.charAt(i);
fos.write(c);
}
System.out.println("利用 文件字节输入 流将 内容
读入");
while(true) {
int r = fis.read();
if(r==-1) break;
System.out.println((char)r);
}
}

2. 积极处理:try…catch…finally

// 2. 积极处理:try..catch..finally
public class Test_01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
String str = "helloworld";
// 文件字节输出流
fos = new
FileOutputStream("file2/test.txt");
for(int i=0;i<str.length();i++) {
char c = str.charAt(i);
fos.write(c);
}
}catch(IOException e) {
e.printStackTrace();
}finally {
if(fos!=null) {
try {
fos.close();//
null.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

3.积极处理:try-with-resources(自动的关闭 try()中的资源)

// 3.积极处理:try-with-resources(自动的关闭 try()
中的资源)
public class Test_02 {
public static void main(String[] args) {
try(
FileOutputStream fos = new
FileOutputStream("file/test.txt");
FileInputStream fis = new
FileInputStream("file/test.txt")
) {
String str = "helloworld";
// 文件字节输出流
for(int i=0;i<str.length();i++) {
char c = str.charAt(i);
fos.write(c);
}
System.out.println("文件字节输入流将内
容读入");
while(true) {
int r = fis.read();
if(r==-1) break;
System.out.println((char)r);
}
}catch(IOException e) {
e.printStackTrace();
}
}
}


举报

相关推荐

0 条评论