二、IO操作基本步骤

一、IO操作基本步骤(非常重要)

(1)创建流

(2)选择流

(3)操作流

(4)关闭流(释放资源)

示例:(经典代码,一定要掌握)

 1 import java.io.*;
 2 public class TestIO02 {
 3     public static void main(String[] args) {
 4         //创建流
 5         File file = new File("b.txt");
 6         //选择流
 7         InputStream inputStream = null;
 8         try {
 9             //操作流
10             inputStream = new FileInputStream(file);
11             int temp;  //当temp等于-1时,表示已经到了文件结尾,停止读取
12             while((temp = inputStream.read()) != -1){
13                 System.out.println((char)temp);
14             }
15         } catch (IOException e) {
16             e.printStackTrace();
17         } finally {
18             //关闭流
19             //这种写法,保证了即使遇到异常情况,也会关闭流对象。
20             if(inputStream != null){
21                 try {
22                     inputStream.close();
23                 } catch (IOException e) {
24                     e.printStackTrace();
25                 }
26             }
27         }
28 
29     }
30 }

这个是改进,常用这种方式

 1 import java.io.*;
 2 public class TestIO03 {
 3     public static void main(String[] args) {
 4         //创建流
 5         File file = new File("b.txt");
 6         //选择流
 7         InputStream inputStream = null;
 8         try {
 9             inputStream = new FileInputStream(file);
10             //操作流
11             byte[] flush = new byte[1024];
12             int len = -1;  //接收长度
13             while ((len = inputStream.read(flush)) != -1){
14                 String str = new String(flush,0,len);
15                 System.out.println(str);
16             }
17         } catch (IOException e) {
18             e.printStackTrace();
19         }finally {
20             //关闭流
21             if(inputStream!=null){
22                 try {
23                     inputStream.close();
24                 } catch (IOException e) {
25                     e.printStackTrace();
26                 }
27             }
28         }
29     }
30 }

猜你喜欢

转载自www.cnblogs.com/qiaoxin11/p/12587698.html