練習用JAVA讀取及寫入TXT檔案,一併順手記錄下來。
會使用到BufferedReader跟FileReader還有FileWriter
先用一支程式來建立TXT檔,再來把這TXT檔案的內容寫到另一個新的文字檔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.FileWriter; public class Write { public static void main(String[] args) { try { // Constructs a FileWriter object given a file name. FileWriter fw = new FileWriter("one.txt"); fw.write("This is one!"); fw.flush(); fw.close(); } catch (Exception e) { System.out.println("Something Error"); } } } |
編譯跟執行一下
1 2 |
javac Write.java java -cp . Write |
就可以在目錄底下看到「one.txt」這個檔案
接下來就到我們的主題了,我們要把這檔案讀出來然後寫入到另一個檔案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; public class ReadAndWrite { public static void main(String[] args) { try { // Creates a new FileReader, given the name of the file to read from. FileReader fr = new FileReader("one.txt"); // Creates a buffering character-input stream that uses a default-sized input buffer. BufferedReader br = new BufferedReader(fr); String content = ""; while (br.ready()) { content = br.readLine(); System.out.println("Ready... read txt"); System.out.println("-------------"); System.out.println(content); System.out.println("-------------"); } // Constructs a FileWriter object given a file name. FileWriter fw = new FileWriter("target.txt"); fw.write(content); fw.flush(); System.out.println("Write Complete!"); // After used close. fr.close(); fw.close(); } catch (Exception e) { System.out.println("Something Error"); } } } |
編譯執行了之後,就會出現「target.txt」的檔案
1 2 |
javac ReadAndWrite.java java -cp . ReadAndWrite |
完成!
之後有機會再分享讀取及寫入多行的方式。