IO流(2)FileInputStream
阿新 • • 發佈:2022-04-13
package IO.inputstream; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class FileInputStream { public static void main(String[] args) { } /** * 演示FileInputStream的使用(位元組輸入流 檔案-->程式) * @author 長空扯淡*/ @Test public void readFile01(){ String filePath = "e:\\hello.txt"; int readDate = 0; java.io.FileInputStream fileInputStream = null; try { //建立FileInputStream物件,用來讀取檔案 fileInputStream = new java.io.FileInputStream(filePath); //從該輸入流讀取一個位元組的資料,如果沒有輸入可用,此方法將阻止//如果返回-1,表示讀取完畢 while((readDate = fileInputStream.read())!=-1){ System.out.print((char)readDate);//轉成char顯示 } } catch (IOException e) { e.printStackTrace(); } finally { //關閉檔案流,釋放資源 try { fileInputStream.close(); }catch (IOException e) { e.printStackTrace(); } } } /** * 使用read(byte[] b)//讀取檔案,提高效率 * @author 長空扯淡 */ @Test public void readFile02(){ String filePath = "e:\\hello.txt"; int readLen = 0; //位元組陣列 byte[] buf = new byte[10];//一次讀取8個位元組 java.io.FileInputStream fileInputStream = null; try { //建立FileInputStream物件,用來讀取檔案 fileInputStream = new java.io.FileInputStream(filePath); //從該輸入流讀取最多b.length位元組的資料到位元組陣列。此方法將阻塞,直到某些輸入可用 //如果返回-1,表示讀取完畢 //如果讀取正常,返回實際讀取的位元組數 while((readLen = fileInputStream.read(buf))!=-1){ System.out.print(new String(buf,0,readLen));//轉成char顯示 } } catch (IOException e) { e.printStackTrace(); } finally { //關閉檔案流,釋放資源 try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }