import java.io.*; import java.util.Scanner; public class FileIOBufferedWriter { public static void main(String[] args) { try { String fileName, fileDir; System.out.println("請輸入檔名: "); Scanner sn = new Scanner(System.in); fileDir = sn.next(); BufferedWriter of = new BufferedWriter(new FileWriter (fileDir)); of.write("以 BufferedWriter 寫入測試"); of.newLine(); of.write("讀取顯示這檔案"); of.newLine(); of.close(); System.out.println("完成寫入檔案: "+ fileDir); }catch(IOException e){ System.out.println("輸入檔案路徑錯誤"); } } }執行結果
檢視輸出檔案
以此方式寫入,每次執行都會清除原來檔案的內容,若要在原檔案附加內容時,需要更改 FileWriter的參數:
BufferedWriter of = new BufferedWriter(new FileWriter (fileDir, true));
沒有留言:
張貼留言