//用PrintWriter寫入文件 import java.io.IOException; import java.io.PrintWriter; public class PrintWriteDemo { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter("01.txt"); out.print("the quick brown fox"); out.println(" jumps over the lazy dog."); out.write("work is like a capricious lover whose "); out.write("incessant demands are resented but who is missed terribly when she is not there\n"); out.close(); //如果不關閉文件,文件停留在buffer zone, 不會寫進"01.txt"中 } }
FileWriter只能寫入文件,無法往文件中追加內容
//用FileWriter寫入和追加文件 import java.io.IOException; import java.io.FileWriter; public class FileWriterDemo { public static void main(String[] args) throws IOException { FileWriter out = new FileWriter("02.txt"); //constructor中添加true,即FileWriter out = new FileWriter("02.txt", true)就是往02.txt中追加文件了 out.write("work is like a capricious lover whose "); out.write("incessant demands are resented but who is missed terribly when she is not there\n"); out.write(98.7 + "\n"); out.close(); //很重要,一定記得關閉文件 } }
都別忘記 throws IOException