2015-02-22 16:16

[Java] 檔案讀寫

FileReader & FileWriter
  1. import java.io.BufferedReader; 
  2. import java.io.BufferedWriter; 
  3. import java.io.FileReader; 
  4. import java.io.FileWriter; 
  5.  
  6. public class FileReadWrite1 { 
  7.  
  8.    public static void main(String[] args) throws Exception { 
  9.  
  10.        FileReader fReader = new FileReader("input.txt"); 
  11.        FileWriter fWriter = new FileWriter("output.txt"); 
  12.  
  13.        /* Buffered 提供單行讀取的功能 */ 
  14.        BufferedReader bReader = new BufferedReader(fReader); 
  15.        BufferedWriter bWriter = new BufferedWriter(fWriter); 
  16.  
  17.        String line; 
  18.        while ((line = bReader.readLine()) != null) { 
  19.            System.out.println(line); 
  20.            bWriter.write(line); 
  21.            bWriter.newLine(); 
  22.        } 
  23.  
  24.        bReader.close(); 
  25.        bWriter.close(); 
  26.    } 
  27. } 


InputStreamReader & OutputStreamWriter
  1. import java.io.BufferedReader; 
  2. import java.io.BufferedWriter; 
  3. import java.io.FileInputStream; 
  4. import java.io.FileOutputStream; 
  5. import java.io.InputStreamReader; 
  6. import java.io.OutputStreamWriter; 
  7.  
  8. public class FileReadWrite2 { 
  9.  
  10.    public static void main(String[] args) throws Exception { 
  11.  
  12.        InputStreamReader fReader = new InputStreamReader( 
  13.            new FileInputStream("input.txt"), "UTF8" 
  14.        ); 
  15.        OutputStreamWriter fWriter = new OutputStreamWriter( 
  16.            new FileOutputStream("output.txt"), "UTF8" 
  17.        ); 
  18.  
  19.        /* Buffered 提供單行讀取的功能 */ 
  20.        BufferedReader bReader = new BufferedReader(fReader); 
  21.        BufferedWriter bWriter = new BufferedWriter(fWriter); 
  22.  
  23.        String line; 
  24.        while ((line = bReader.readLine()) != null) { 
  25.            System.out.println(line); 
  26.            bWriter.write(line); 
  27.            bWriter.newLine(); 
  28.        } 
  29.  
  30.        bReader.close(); 
  31.        bWriter.close(); 
  32.    } 
  33. } 

0 回應: