3.16Java基础总结 IO全部

I/O全部

in.read 读入
out.write 写出

Java操作流的通用方法
1、创建管道
2、读写操作
3、关闭管道
关闭管道从小到大,全部都关闭,增强代码的健壮性

流的分类:
字节流:InputStream、BufferedInputStream、FileInputStream Out
字符流:Reader、Writer、BufferedReader
对象流:
写入文件→序列化
从文件读取对象,反序列化,产生对象,要实现serializable接口

写操作时,多一步flush操作,冲刷,立即生效
构造加一个true ,从末尾处write

File文件类常用方法
exists isdirectory createNewfile mkdir isFile

常用流new的过程
FileInputStream → BufferedInputStream

FIleOutputStream → BufferedOutputStream → DataOutputStream

File → FileOutputStream → PrintSteam

FileReader → BufferedReader

FileInputStream → InputStreamReader → BufferedReader

 

 1 package com.io;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 /*I/O流
 8  
 9  in,read,读操作,从数据源读,流入
10  * 
11  */
12 public class InputStreamTest {
13     public static void main(String[] args) {
14         //File
15         //String filePath
16         try {
17             InputStream in = new FileInputStream("file/test.txt");
18             
19 //            int i = 0;
20 //            
21 //            while(true){
22 //                if((i = in.read()) != -1){
23 //                    System.out.println(i);
24 //                }else{
25 //                    break;
26 //                }
27 //            }
28             
29             int i = 0;
30             byte[] by = new byte[1024];
31             while(true){
32                 if((i = in.read(by)) != -1){
33                     
34                 }else{
35                     break;
36                 }
37             }
38             
39             String info = new String(by);
40             
41             String [] a = info.split("@");
42             
43             System.out.println(a[0] + " "  + a[1].trim());
44             
45             in.close();
46         } catch (FileNotFoundException e) {
47             e.printStackTrace();
48         } catch (IOException e) {
49             // TODO Auto-generated catch block
50             e.printStackTrace();
51         }
52         
53     }
54 }
InputStream
 1 package com.io;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.OutputStream;
 7 
 8 public class OutputStreamTest {
 9 
10     /**
11      * @param args
12      */
13     public static void main(String[] args) {
14         try {
15             OutputStream out = new FileOutputStream("file/test.txt", true);
16             String str = "zhangsan@123";
17             
18             out.write(str.getBytes());
19             
20             out.flush();//多一步刷新操作
21             out.close();
22         } catch (FileNotFoundException e) {
23             
24             e.printStackTrace();
25         } catch (IOException e) {
26             // TODO Auto-generated catch block
27             e.printStackTrace();
28         }
29 
30     }
31 
32 }
OutputStream
 1 package com.io;
 2 
 3 //按字节读取TXT文件
 4 import java.io.File;
 5 import java.io.FileInputStream;
 6 import java.io.FileNotFoundException;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 
10 
11 
12 
13 public class ReadByChars {
14     public static void main(String[] args) {        
15         File file = new File("d:/bankinfo.txt");
16         InputStream in = null;
17         byte[] tempByte = new byte[1024];
18         int byteread = 0;
19         try {
20             System.out.println("以字节为单位读取文件内容,一次读多个字节:");
21             in = new FileInputStream(file);
22             while ((byteread = in.read(tempByte)) != -1) {
23                 System.out.write(tempByte, 0, byteread);
24             }
25         } catch (FileNotFoundException e) {
26             e.printStackTrace();
27         } catch (IOException e) {
28             e.printStackTrace();
29         } finally {
30             if (in != null) {
31                 try {
32                     in.close();
33                 } catch (IOException e) {
34                     e.printStackTrace();
35                 }
36             }
37         }
38     }
39 }
ReadByChars
 1 package com.io;
 2 
 3 //按行读取TXT文件
 4 
 5 import java.io.BufferedReader;
 6 
 7 import java.io.File;
 8 
 9 import java.io.FileNotFoundException;
10 
11 import java.io.FileReader;
12 
13 import java.io.IOException;
14 
15 public class ReadLine {
16 
17     public static void main(String[] args) {
18         File file = new File("d:/bankinfo.txt");
19         BufferedReader reader = null;
20         String tempString = null;
21         int line = 1;
22 
23         try {
24             System.out.println("以行为单位读取文件内容,一次读一整行:");
25             reader = new BufferedReader(new FileReader(file));
26             while ((tempString = reader.readLine()) != null) {
27                 System.out.println("Line" + line + ':' + tempString);
28                 line++;
29             }
30             reader.close();
31         } catch (FileNotFoundException e) {
32             e.printStackTrace();
33         } catch (IOException e) {
34             e.printStackTrace();
35         } finally {
36             if (reader != null) {
37                 try {
38                     reader.close();
39                 } catch (IOException e) {
40                     e.printStackTrace();
41                 }
42             }
43         }
44 
45     }
46 }
ReadLine
 1 package com.io;
 2 
 3 import java.io.*;
 4   public class DataStreamTest {
 5       public static void main( String args[] ) {
 6         int data[] = {100,101,102,103,104,105};
 7         int t;
 8         try{
 9             DataOutputStream out = new  DataOutputStream (new  FileOutputStream("dest.txt"));
10             for(int i = 0; i < data.length; i++) 
11                 out.writeInt(data[i]);
12             out.close();
13              DataInputStream in = new  DataInputStream (new  FileInputStream("dest.txt"));
14              for(int i = 0;i < data.length; i++) {
15                  t = in.readInt();
16             System.out.print(" "+t);
17              }
18              System.out.println( );
19              in.close();
20         }catch(IOException e){
21             System.out.println(e.getMessage());}
22           }
23 }
DataStream
 1 package com.io;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.ObjectInputStream;
 8 import java.io.ObjectOutputStream;
 9 import java.util.HashSet;
10 import java.util.Set;
11 
12 /**
13  * Date: 2016-3-18-下午2:56:15
14  * Class_name: ObjectStreamDemo.java
15  * Package_name: com.lovo.demo_17
16  * Author: ZhangYue
17  * Description: 
18  */
19 public class ObjectStreamDemo {
20 
21     /**
22      * @param args
23      */
24     public static void main(String[] args) {
25         
26         //ObjectOutputStream
27         
28         try {
29             ObjectOutputStream outObj = new ObjectOutputStream(new FileOutputStream("file/object.txt"));
30             
31             Student stu1 = new Student("张三", 22, "男");
32             Student stu2 = new Student("李四", 24, "男");
33             
34             Set<Student> stus = new HashSet<Student>();
35             stus.add(stu1);
36             stus.add(stu2);
37             
38             outObj.writeObject(stus);
39             
40             outObj.close();
41             
42         } catch (FileNotFoundException e) {
43             // TODO Auto-generated catch block
44             e.printStackTrace();
45         } catch (IOException e) {
46             // TODO Auto-generated catch block
47             e.printStackTrace();
48         }
49         
50         
51         //ObjectInputStream 
52         try {
53             ObjectInputStream inObj = new ObjectInputStream(new FileInputStream("file/object.txt"));
54             
55             Object obj = inObj.readObject();
56             
57             Set<Student> stu = (Set<Student>)obj;
58             
59             for(Student su : stu){
60                 System.out.println(su.getName());
61                 System.out.println(su.getAge());
62                 System.out.println(su.getGender());
63             }
64             
65             inObj.close();
66         } catch (FileNotFoundException e) {
67             // TODO Auto-generated catch block
68             e.printStackTrace();
69         } catch (IOException e) {
70             // TODO Auto-generated catch block
71             e.printStackTrace();
72         } catch (ClassNotFoundException e) {
73             // TODO Auto-generated catch block
74             e.printStackTrace();
75         }
76         
77     }
78 
79 }
ObjectStream
  1 package com.io;
  2 import java.io.BufferedReader;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.FileReader;
  8 import java.io.IOException;
  9 import java.io.InputStreamReader;
 10 import java.io.PrintWriter;
 11 //package com.b510.txt;
 12 //d:/bankinfo.txt
 13 /**
 14  * @author Hongten
 15  * 读写TXT原码
 16  * @time 2011-12-12 2011
 17  */
 18 public class WriteReadTxt {
 19     public static void main(String[] args) {
 20         WriteReadTxt myFile = new WriteReadTxt();
 21         try {
 22             for (int i = 0; i < 5; i++) {
 23                 myFile.creatTxtFile("b510");
 24                 myFile.writeTxtFile("现在写入数字" + i);
 25                 String str = myFile.readDate();
 26                 System.out.println("*********\n" + str);
 27             }
 28         } catch (IOException e) {
 29             e.printStackTrace();
 30         }
 31     }
 32 
 33     private static String path = "d:/";
 34     private static String filenameTemp;
 35 
 36     
 37     // 创建文件
 38     public static boolean creatTxtFile(String name) throws IOException {
 39         boolean flag = false;
 40         filenameTemp = path + name + ".txt";
 41         File filename = new File(filenameTemp);
 42         if (!filename.exists()) {
 43             filename.createNewFile();
 44             flag = true;
 45         }
 46         return flag;
 47     }
 48 
 49 
 50     //写文件
 51     //newStr
 52     public static boolean writeTxtFile(String newStr) throws IOException {
 53         // 先读取原有文件内容,然后进行写入操作
 54         boolean flag = false;
 55         String filein = newStr + "\r\n";
 56         String temp = "";
 57 
 58         FileInputStream fis = null;
 59         InputStreamReader isr = null;
 60         BufferedReader br = null;
 61 
 62         FileOutputStream fos = null;
 63         PrintWriter pw = null;
 64         try {
 65             // 文件路径
 66             File file = new File(filenameTemp);
 67             // 将文件读入输入流
 68             fis = new FileInputStream(file);
 69             isr = new InputStreamReader(fis);
 70             br = new BufferedReader(isr);
 71             StringBuffer buf = new StringBuffer();
 72 
 73             // 保存该文件原有的内容
 74             for (int j = 1; (temp = br.readLine()) != null; j++) {
 75                 buf = buf.append(temp);
 76                 // System.getProperty("line.separator")
 77                 // 行与行之间的分隔符 相当于“\n”
 78                 buf = buf.append(System.getProperty("line.separator"));
 79             }
 80             buf.append(filein);
 81 
 82             fos = new FileOutputStream(file);
 83             pw = new PrintWriter(fos);
 84             pw.write(buf.toString().toCharArray());
 85             pw.flush();
 86             flag = true;
 87         } catch (IOException e1) {
 88             // TODO 自动生成 catch 块
 89             throw e1;
 90         } finally {
 91             if (pw != null) {
 92                 pw.close();
 93             }
 94             if (fos != null) {
 95                 fos.close();
 96             }
 97             if (br != null) {
 98                 br.close();
 99             }
100             if (isr != null) {
101                 isr.close();
102             }
103             if (fis != null) {
104                 fis.close();
105             }
106         }
107         return flag;
108     }
109 
110     /**
111      * 读取数据
112      */
113     public void readData1() {
114         try {
115             FileReader read = new FileReader(filenameTemp);
116             BufferedReader br = new BufferedReader(read);
117             String row;
118             while ((row = br.readLine()) != null) {
119                 System.out.println(row);
120             }
121         } catch (FileNotFoundException e) {
122             e.printStackTrace();
123         } catch (IOException e) {
124             e.printStackTrace();
125         }
126     }
127 
128     public String readDate() {
129         // 定义一个待返回的空字符串
130         String strs = "";
131         try {
132             FileReader read = new FileReader(new File(filenameTemp));
133             StringBuffer sb = new StringBuffer();
134             char ch[] = new char[1024];
135             int d = read.read(ch);
136             while (d != -1) {
137                 String str = new String(ch, 0, d);
138                 sb.append(str);
139                 d = read.read(ch);
140             }
141             System.out.print(sb.toString());
142             String a = sb.toString().replaceAll("@@@@@", ",");
143             strs = a.substring(0, a.length() - 1);
144         } catch (FileNotFoundException e) {
145             e.printStackTrace();
146         } catch (IOException e) {
147             e.printStackTrace();
148         }
149         return strs;
150     }
151 }
WriteReadTxt

 

1、使用字节流将10个学生的成绩写入文件 score.txt
2、使用字符流将这些成绩读取出来,并保存到List集合中
3、创建Student类(姓名、学号、成绩),以成绩集合里的成绩为依据,创建学生对象(姓名、学号自定)
4、使用对象流将所有的学生对象写入文件 student.txt

 1 package com.io.teacher;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashSet;
 5 import java.util.List;
 6 import java.util.Set;
 7 
 8 /**
 9  * Date: 2016-3-18-下午4:03:50
10 1、使用字节流将10个学生的成绩写入文件 score.txt
11 2、使用字符流将这些成绩读取出来,并保存到List集合中
12 3、创建Student类(姓名、学号、成绩),以成绩集合里的成绩为依据,创建学生对象(姓名、学号自定)
13 4、使用对象流将所有的学生对象写入文件 student.txt
14  */
15 public class Test {
16 
17     /**
18      * @param args
19      */
20     public static void main(String[] args) {
21         // TODO Auto-generated method stub
22         byte[] scores = new byte[10];
23         scores[0] = 40;
24         scores[1] = 50;
25         scores[2] = 60;
26         scores[3] = 70;
27         scores[4] = 80;
28         scores[5] = 90;
29         scores[6] = 100;
30         scores[7] = 110;
31         scores[8] = 120;
32         scores[9] = 121;
33         
34         //存入成绩
35         StudentStream.saveScore(scores, "file/score.txt");
36         
37         //读出成绩
38         byte[] scors = StudentStream.readScore("file/score.txt");
39         
40         //装入List
41         List<Integer> scoreList = new ArrayList<Integer> ();
42         for(int i = 0; i < scors.length; i++){
43             scoreList.add((int)scors[i]);
44         }
45         
46         Set<Student> stus = new HashSet<Student>();    
47         
48         //以成绩为依据创建学生对象
49         for(Integer in : scoreList){
50             stus.add(new Student("张三" + in, in*2 , in));
51 //            System.out.println(in);
52         }
53         
54         //对象流将学生对象写入文件student.txt
55         StudentStream.saveStudents(stus, "file/student.txt");
56     }
57 
58 }
TestMain
 1 package com.io.teacher;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 import java.io.ObjectOutputStream;
10 import java.io.OutputStream;
11 import java.util.Set;
12 
13 /**
14  * Date: 2016-3-18-下午4:00:53
15  * Class_name: StudentStream.java
16  * Package_name: com.lovo.demo_17_2
17  * Author: ZhangYue
18  * Description: 
19  */
20 public class StudentStream {
21 
22     
23     public static void saveScore(byte[] scores, String filePath){
24         
25         try {
26             File file = new File(filePath);
27     
28             if(!file.exists()){
29                 file.createNewFile();
30             }
31             
32             OutputStream out = new FileOutputStream(file);
33             out.write(scores);
34             out.close();
35             
36         } catch (FileNotFoundException e) {
37             e.printStackTrace();
38         } catch (IOException e) {
39             e.printStackTrace();
40         }
41     }
42 
43     public static byte[] readScore(String filePath){
44         byte[] by = new byte[20];
45         
46         try {
47             File file = new File(filePath);
48             
49             if(!file.exists()){
50                 file.createNewFile();
51             }
52             
53             InputStream in = new FileInputStream(file);
54             
55             int count = in.available();
56             
57             by = new byte[count];
58             
59             in.read(by);
60             
61             in.close();
62         } catch (FileNotFoundException e) {
63             e.printStackTrace();
64         } catch (IOException e) {
65             // TODO Auto-generated catch block
66             e.printStackTrace();
67         }
68         
69         return by;
70     }
71     
72     public static void saveStudents(Set<Student> stus, String filePath){
73         try {
74             File file = new File(filePath);
75             
76             if(!file.exists()){
77                 file.createNewFile();
78             }
79             
80             ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
81             
82             out.writeObject(stus);
83             
84             out.close();
85         } catch (FileNotFoundException e) {
86             e.printStackTrace();
87         } catch (IOException e) {
88             // TODO Auto-generated catch block
89             e.printStackTrace();
90         }
91     }
92 }
StudentStream
 1 package com.io.teacher;
 2 
 3 
 4 
 5 import java.io.Serializable;
 6 
 7 public class Student implements Serializable{
 8 
 9     private String name;
10     private int number;
11     private int score;
12     
13     public Student() {
14         super();
15     }
16 
17     public Student(String name, int number, int score) {
18         super();
19         this.name = name;
20         this.number = number;
21         this.score = score;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     public int getNumber() {
33         return number;
34     }
35 
36     public void setNumber(int number) {
37         this.number = number;
38     }
39 
40     public int getScore() {
41         return score;
42     }
43 
44     public void setScore(int score) {
45         this.score = score;
46     }
47     
48     
49     
50 }
Student

 

posted @ 2016-03-22 22:38  远秋  阅读(175)  评论(0编辑  收藏  举报