IO流的异常处理方式
IO流的异常处理方式:为防止代码异常导致流无法关闭,因此在finally中对流进行关闭。
示例3:
1.import java.io.FileWriter;
2.import java.io.IOException;
3.
4.public class IOExceptionDemo{
5. public static void main(String[] args){
6.
7. FileWriter fw = null;
8.
9. try{
10. fw = new FileWriter("demo.txt" );
11.
12. fw.write( "abcde");
13. } catch(IOException e){
14. System.out.println(e.toString());
15. } finally{
16. try{
17. fw.close();
18. } catch(IOException e){
19. throw new RuntimeException("关闭失败");
20. }
21. }
22. }
23.}
24.
运行结果:
需求:读取一个文文件,将读取到的字符打印到控制台。(使用FileReader)第一种读取方式:使用read()方法读取文本文件数据。
示例4:
1.import java.io.FileReader;
2.import java.io.IOException;
3.
4.public class FileReaderDemo{
5. public static void main(String[] args) throws IOException{
6.
7. FileReader fr = new FileReader("demo.txt" );
8.
9. //用Reader中的read方法读取字符
10. int ch = 0;
11.
12. while((ch = fr.read()) != -1){
13. System.out.println(( char)ch);
14. }
15.
16. fr.close();
17. }
18.}
19.
运行结果:
说明:
第二种读取方式:使用read(char[])方法读取文本文件数据。
示例5:
1.import java.io.FileReader;
2.import java.io.IOException;
3.
4.public class FileReaderDemo{
5. public static void main(String[] args)throws IOException{
6. FileReader fr = new FileReader("demo.txt" );
7.
8. //使用read(char[])读取文本文件数据
9. //先创建字符数组
10. char[] buf = new char[3];
11.
12. int len = 0;
13.
14. while((len = fr.read(buf)) != -1){
15. System.out.println( new String(buf,0,len));
16. }
17.
18. fr.close();
19. }
20.}
21.
运行结果: