javaIO操作之字節輸入流--InputStream
阿新 • • 發佈:2017-08-17
bsp system com cep exceptio 說明 foo 方式 輸入
/** *<li> InputStream類中定義的方法: * <li>讀取的數據保存在字節數組中,返回讀取的字節數組的長度:public int read(byte[] b) throws IOException ; * <li>讀取部分數據保存在字節數組中,返回讀取數據的長度:public int read(byte[] b,int off,int len)throws IOException ; * 如果文件內容讀取到結尾字返回-1; */ package com.java.demo; importjava.io.File; import java.io.FileInputStream; import java.io.InputStream; public class TestDemo { public static void main(String args[]) throws Exception{ //設置文件路徑 File fl = new File("e:"+File.separator+"hello" + File.separator+"demo" +File.separator+"java.txt" ); if(fl.exists()){ //文件存在 InputStream in = new FileInputStream(fl) ; byte data[] = new byte[1]; int len = in.read(data) ;//將讀取的內容保存在字節數組中,並且返回字節長度 System.out.println("【"+new String(data,0,len) +"】"); } } }
重要的實現方式:public abstract int read() throws IOException ;
/** *<li>讀取單個字節,如果讀取到最後則返回-1: public abstract int read()throws IOException ; */ package com.java.demo; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; public class TestDemo { public static void main(String args[]) throws Exception{ //設置文件路徑 File fl = new File("e:"+File.separator+"hello" + File.separator+"demo" +File.separator+"java.txt" ); if(fl.exists()){ //文件存在 InputStream in = new FileInputStream(fl) ; byte data[] = new byte[1024]; int foot = 0 ; int temp = 0 ; while((temp = in.read()) != -1){ //說明存在數據 data[foot ++] = (byte)temp;//將讀取的數據保存在字節數組中 } in.close(); System.out.println("[" + new String(data,0,foot)+"]"); } } }
javaIO操作之字節輸入流--InputStream