從頭認識java-16.3 IO的典型用法

來源:互聯網
上載者:User

從頭認識java-16.3 IO的典型用法

解釋:由於IO裡面的InputStream,OutputStream這些api的用法比較簡單,因此,暫時沒有略過。

這一章節主要介紹一下IO的典型用法。

1.使用IO的時候推薦在外麵包一層Buffer

 

package com.ray.ch16;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {FileReader fileReader = new FileReader("d:\\fg.ini");//這裡需要自己定義你想讀取的檔案BufferedReader bufferedReader = new BufferedReader(fileReader);String text = "";while ((text = bufferedReader.readLine()) != null) {System.out.println(text);}System.out.println("-------------------------------------");FileInputStream fis = new FileInputStream("d:\\fg.ini");BufferedInputStream bis = new BufferedInputStream(fis);byte b[] = new byte[1024];int len = 0;int temp = 0; // 所有讀取的內容都使用temp接收while ((temp = bis.read()) != -1) { // 當沒有讀取完時,繼續讀取b[len] = (byte) temp;len++;}System.out.println(new String(b, 0, len));}}

上面的代碼是兩種讀取某個檔案內容的方法,分別通過FileInputStream和FileReader實現。

 

還有一點需要注意的是,在使用完這些InputStream的資源後,必須關閉,不然很容易引起記憶體溢出,我上面的代碼就沒有做好這一點。

 

2.使用DataInputStream格式化輸入輸出

 

package com.ray.ch16;import java.io.DataInputStream;import java.io.FileInputStream;import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {DataInputStream dataInputStream = new DataInputStream(new FileInputStream("d:\\fg.ini"));while (dataInputStream.available() != 0) {System.out.println(dataInputStream.read());//System.out.println(dataInputStream.readDouble());//System.out.println(dataInputStream.readInt());}}}

總結:這一章節主要介紹IO的典型用法的兩個典型用法。

 

聯繫我們

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