2014/07/11

[Java] FileIO 讀寫檔案




讀取:

Example1:一般讀檔

用到FileReader和BufferedReader

?
1
2
FileReader fileReader = new FileReader("檔案路徑");
BufferedReader bufferedReader = new BufferedReader(fileReader);

檔案讀取:(按行)

?
1
bufferedReader.readLine();

關閉檔案:

?
1
fileReader.close();

範例程式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package p3;
import java.io.BufferedReader;
import java.io.FileReader;
public class FileReadDemo {
    public static void main(String args[]){
        FileReader fileReader;
        try {
            fileReader = new FileReader("檔案路徑");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            while (bufferedReader.ready()){
                System.out.println(bufferedReader.readLine());
            }
            fileReader.close();
        } catch (Exception e) {
            System.out.println(e);
        }
         
    }
}


Example2:按照編碼讀檔


用到FIle, FileInputStream, InputStreamReader, BufferedReader

?
1
2
3
4
File file = new File("檔案路徑");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"編碼");
BufferedReader bufferedReader = new BufferedReader(isr);

範例程式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package p3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileReadDemo {
    public static void main(String args[]){
        try {
            File file = new File("/Users/apple/Desktop/info.txt");
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis,"utf8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            while (bufferedReader.ready()){
                System.out.println(bufferedReader.readLine());
            }
        } catch (Exception e) {
            System.out.println(e);
        }
         
    }
}

寫入:

Example:

用到FileWriter

?
1
FileWriter fileWriter = new FileWriter("檔案路徑");

範例程式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package p3;
import java.io.FileWriter;
public class FileWriteDemo {
    public static void main(String args[]){
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter("檔案路徑");
            fileWriter.write("輸出內容");
            fileWriter.flush();
            fileWriter.close();
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}