Java學習(2):將鍵盤錄入的內容儲存到指定檔案中

來源:互聯網
上載者:User

標籤: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):將鍵盤錄入的內容儲存到指定檔案中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.