從頭認識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的典型用法的兩個典型用法。