java簡單地讀寫檔案 和 鍵盤輸入

來源:互聯網
上載者:User

總是忘記java讀寫檔案的代碼具體怎麼寫,寫了一個記錄如下

String filename="mydict.txt";<br />File file=new File(filename);<br />//read file<br />if(file.exists())<br />{<br />try<br />{<br />BufferedReader br=new BufferedReader(new FileReader(file));<br />String temp=null;<br />while((temp=br.readLine())!=null)<br />{<br />System.out.println(temp);</p><p>}<br />}<br />catch(FileNotFoundException e)<br />{<br />System.err.println(e.getMessage());<br />}<br />catch(IOException e1)<br />{<br />System.err.println(e1.getMessage());</p><p>}</p><p>}<br />else<br />{<br />System.out.println("file does not exist...");<br />}</p><p>//write file, cover the old content<br />//write the key sentences<br />try<br />{<br />BufferedWriter bw=new BufferedWriter(new FileWriter(file));<br />String s="fdjsaifjdisaof";<br />bw.write(s);<br />bw.close();<br />}<br />catch(IOException e)<br />{<br />//.......<br />}<br />

 

 注意:bufferedwriter預設大小是說足夠大,建構函式中可以定義緩衝區的大小單位應該是byte,如果把緩衝區定義的非常大,而最後沒有flush的話,有可能你會發現檔案中並沒有內容

bufferedWriter只是把放到緩衝區中,等緩衝區滿了以後才會一次寫入檔案中,預設緩衝區的大小是1024個位元組,如果小於1024個位元組的話,實際上內容都在緩衝區中,並不寫入檔案,這是就要調用.flush方法對緩衝區進行一次重新整理,這樣就算緩衝區沒滿也會把內容輸出。

接受console輸入:

java.util.Scanner sc = new Scanner(System.in);<br />String input = sc.next();</p><p>或</p><p>BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );<br />String input = br.readLine();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.