BufferedReader類和BufferedWriter類
阿新 • • 發佈:2018-12-31
由鍵盤輸入多行字元並寫入指定檔案中,以end字串結束
1.效果圖
2. Java程式碼
package com.example.demo.stream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import com.example.demo.file.FileTest; /** * @Description BufferedReader類和BufferedWriter類 * @author 大都督 * @date 2018年12月25日 */ public class BufferedReaderAndBufferedWriterTest { public static void main(String[] args) throws IOException { File file = FileTest.createFile(FileTest.parent, "b_r_w.txt"); //由鍵盤輸入多行字元並寫入指定檔案中,以end字串結束 keyboardInputOnFile(file); } /** * @Title: keyboardInputOnFile * @Description: 由鍵盤輸入多行字元並寫入指定檔案中,以end字串結束 * @param file * @author 大都督 * @date 2018年12月25日 * @return void * @throws IOException */ private static void keyboardInputOnFile(File file) throws IOException { System.out.println("請輸入內容:"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file)); String line = null; try { while (!(line = bufferedReader.readLine()).equals("end")) { bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedReader.close(); bufferedWriter.close(); } catch (Exception e) { e.printStackTrace(); } } }