標籤:2017年 建立 檔案路徑 結束 沒有 throw 接受 模式 with
要求:儲存鍵盤錄入的內容,當鍵盤輸入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):將鍵盤錄入的內容儲存到指定檔案中