1. 程式人生 > >Java 文件讀寫操作

Java 文件讀寫操作

顯示行號 splay pri images amp index 文件內容 ges 顯示

1【1】按字節讀寫,一次只讀取一個字節,效率比較低

 1 package bk1;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 
 9 
10 public class Dx1 {
11     public void display() //按字節讀取文件內容,每次只能讀取一個字節
12     {
13         File file =new File("課表.txt");//
用來傳文件的名字 14 InputStream in = null; 15 try{ 16 in=new FileInputStream(file); 17 18 19 20 21 int zijie; 22 System.out.println("按字節讀出的結果"); 23 while((zijie=in.read())!=-1) 24 { 25 System.out.write(zijie);
26 } 27 in.close(); 28 } 29 catch (IOException e) { 30 // TODO: handle exception 31 System.out.println(e.getMessage()); 32 return;//退出程序 33 } 34 } 35 36 public static void main(String[] args) throws IOException { 37 //
TODO Auto-generated method stub 38 Dx1 D=new Dx1(); 39 D.display(); 40 } 41 42 }

【2】按字節讀寫,一次可以讀寫多個字節

 1 package bk1;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 
 8 public class Dx2 {
 9     public void display()
10 
11     {
12         File file =new File("課表.txt");
13         InputStream in = null;
14         try {
15             System.out.println("以字節為單位讀取文件內容,一次讀多個字節:");
16             // 一次讀多個字節
17             byte[] tempbytes = new byte[100];
18             int byteread = 0;
19             in = new FileInputStream("課表.txt");
20             Dx2.showAvailableBytes(in);
21             // 讀入多個字節到字節數組中,byteread為一次讀入的字節數
22             while ((byteread = in.read(tempbytes)) != -1) {
23                 System.out.write(tempbytes, 0, byteread);
24             }
25         } catch (Exception e1) {
26             e1.printStackTrace();
27         } finally {
28             if (in != null) {
29                 try {
30                     in.close();
31                 } catch (IOException e1) {
32                 }
33             }
34         }
35     }
36     static void showAvailableBytes(InputStream in) {
37         try {
38             System.out.println("當前字節輸入流中的字節數為:" + in.available());
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42     }
43     
44     public static void main(String[] args) {
45         // TODO Auto-generated method stub
46         Dx2 D=new Dx2();
47         D.display();
48     }
49 
50 }

2【1】以字符為單位讀取文件內容,一次讀一個字符

【2】以字符為單位讀取文件內容,一次讀多個字符

 1 package bk1;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.io.Reader;
 8 
 9 public class Dx3 {
10     public static void readFileByChars(String fileName) {
11         File file = new File("課表.txt");
12         Reader reader = null;
13         try {
14             System.out.println("以字符為單位讀取文件內容,一次讀一個字符:");
15             // 一次讀一個字符
16             
17             reader=new InputStreamReader(new FileInputStream(file));
18             int tempchar;
19             while ((tempchar = reader.read()) != -1) {
20                 // 對於windows下,rn這兩個字符在一起時,表示一個換行。
21                 // 但如果這兩個字符分開顯示時,會換兩次行。
22                 // 因此,屏蔽掉r,或者屏蔽n。否則,將會多出很多空行。
23                 if (((char) tempchar) != ‘r‘) {
24                     System.out.print((char) tempchar);
25                 }
26             }
27             reader.close();
28         } catch (Exception e) {
29             e.printStackTrace();
30         }
31         try {
32             System.out.println("以字符為單位讀取文件內容,一次讀多個字符:");
33             // 一次讀多個字符
34             char[] tempchars = new char[30];
35             int charread = 0;
36             reader = new InputStreamReader(new FileInputStream("課表.txt"));
37             // 讀入多個字符到字符數組中,charread為一次讀取字符數
38             while ((charread = reader.read(tempchars)) != -1) {
39                 // 同樣屏蔽掉r不顯示
40                 if ((charread == tempchars.length)
41                         && (tempchars[tempchars.length - 1] != ‘r‘)) {
42                     System.out.print(tempchars);
43                 } else {
44                     for (int i = 0; i < charread; i++) {
45                         if (tempchars[i] == ‘r‘) {
46                             continue;
47                         } else {
48                             System.out.print(tempchars[i]);
49                         }
50                     }
51                 }
52             }
53         } catch (Exception e1) {
54             e1.printStackTrace();
55         } finally {
56             if (reader != null) {
57                 try {
58                     reader.close();
59                 } catch (IOException e1) {
60                 }
61             }
62         }
63     }
64 
65     public static void main(String[] args) {
66         // TODO Auto-generated method stub
67         Dx3.readFileByChars("課表.txt");
68     }
69 
70 }

截圖:

技術分享圖片

技術分享圖片

文件中的r字符無法讀出。

3以行為單位讀取文件內容,一次讀一整行

 1 package bk1;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.File;
 5 import java.io.FileReader;
 6 import java.io.IOException;
 7 
 8 public class Dx4 {
 9     public static void readFileByLines(String fileName) {
10         File file = new File("課表.txt");
11         BufferedReader reader = null;
12         try {
13             System.out.println("以行為單位讀取文件內容,一次讀一整行:");
14             reader = new BufferedReader(new FileReader(file));
15             String tempString = null;
16             int line = 1;
17             // 一次讀入一行,直到讀入null為文件結束
18             while ((tempString = reader.readLine()) != null) {
19                 // 顯示行號
20                 System.out.println("line " + line + ": " + tempString);
21                 line++;
22             }
23             reader.close();
24         } catch (IOException e) {
25             e.printStackTrace();
26         } finally {
27             if (reader != null) {
28                 try {
29                     reader.close();
30                 } catch (IOException e1) {
31                 }
32             }
33         }
34     }
35 
36     public static void main(String[] args) {
37         // TODO Auto-generated method stub
38         Dx4.readFileByLines("課表.txt");
39 
40     }
41 
42 }

4隨機讀取一段文件內容

package bk1;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Dx5 {
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("隨機讀取一段文件內容:");
            // 打開一個隨機訪問文件流,按只讀方式
            randomFile = new RandomAccessFile("課表.txt", "r");
            // 文件長度,字節數
            long fileLength = randomFile.length();
            // 讀文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 將讀文件的開始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次讀10個字節,如果文件內容不足10個字節,則讀剩下的字節。
            // 將一次讀取的字節數賦給byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Dx5.readFileByRandomAccess("課表.txt");
    }

}

Java 文件讀寫操作