1. 程式人生 > >Java學習(2):將鍵盤錄入的內容保存到指定文件中

Java學習(2):將鍵盤錄入的內容保存到指定文件中

stream exce 創建 txt 關閉 如果 下午 line 再次

要求:保存鍵盤錄入的內容,當鍵盤輸入end時,錄入結束。

 1 /**
 2  * 保存鍵盤輸入,並以end結束
 3  * 
 4  * @author xcx
 5  * @time 2017年6月24日下午3:32:50
 6  */
 7 public class GetData {
 8 
 9     public static void main(String[] args) throws IOException {
10         String fileName = "d:\\java\\jj\\dd.txt";// 要寫入的文件路徑
11         File file = new
File(fileName);// 創建文件對象 12 writefile(file); 13 } 14 15 // 向文件中寫入 16 public static void writefile(File file) throws IOException { 17 // 判斷是否有該文件路徑 18 if (file.getParentFile().exists()) { 19 // 判斷是否有這個文件,如果沒有就創建它 20 if (!file.exists()) { 21 file.createNewFile();
22 } 23 // 創建鍵盤錄入對象 24 Scanner sc = new Scanner(System.in); 25 // 獲得鍵盤錄入字符並判斷 26 String s = sc.nextLine(); 27 while (!s.endsWith("end")) { 28 // 創建輸出字節流 29 FileOutputStream fos = new FileOutputStream(file, true
); 30 // 將輸出字節流轉化為字符流 31 OutputStreamWriter osw = new OutputStreamWriter(fos); 32 // 將字符流轉化為緩存模式 33 BufferedWriter bw = new BufferedWriter(osw); 34 // 寫入 35 bw.write(s); 36 // 關閉輸出流 37 bw.close(); 38 osw.close(); 39 fos.close(); 40 // 再次接受鍵盤錄入 41 s = sc.nextLine(); 42 } 43 44 }else{ 45 System.out.println("你指定的文件路徑不存在,請重新檢查文件路徑"); 46 } 47 } 48 49 }

Java學習(2):將鍵盤錄入的內容保存到指定文件中