JAVA基礎------IO操作(二)__JAVA

來源:互聯網
上載者:User
 

字元流

【向檔案中寫入資料】

現在我們使用字元流

              /**           * 字元流           * 寫入資料           * */         import java.io.*;          class hello{              public static void main(String[] args) throws IOException {                  String fileName="D:"+File.separator+"hello.txt";                  File f=new File(fileName);                  Writer out =new FileWriter(f);                  String str="hello";                  out.write(str);                  out.close();              }          }       

當你開啟hello。txt的時候,會看到hello

其實這個例子上之前的例子沒什麼區別,只是你可以直接輸入字串,而不需要你將字串轉化為位元組數組。

當你如果想問檔案中追加內容的時候,可以使用將上面的聲明out的哪一行換為:

Writer out =new FileWriter(f,true);

這樣,當你運行程式的時候,會發現檔案內容變為:

hellohello如果想在檔案中換行的話,需要使用“\r\n”

比如將str變為String str="\r\nhello";

這樣檔案追加的str的內容就會換行了。

從檔案中讀內容:

              /**           * 字元流           * 從檔案中讀出內容           * */         import java.io.*;          class hello{              public static void main(String[] args) throws IOException {                  String fileName="D:"+File.separator+"hello.txt";                  File f=new File(fileName);                  char[] ch=new char[100];          <

聯繫我們

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