1. 程式人生 > >Java——IO類,字節流讀數據

Java——IO類,字節流讀數據

fhe mcc bob fileinput wot mha ol3 8K src

字節流讀取數據 InputStream
?FileInputStream;
FileInputStream的構造方法 ?FileInputStream(File file); //構造對象不比要求文件存在,會自動創建文件
?FileInputStream(String name);
FileInputStream的成員方法 ?public int read(); //read 讀完一次會自動偏移到下一個字節,返回一共讀到字節長度,讀完文件尾就返回-1; ?
public int read(byte[] b);
?int read(byte[] b, int off, int len);
public class IOTest2 {
public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("1.txt"); //int read = fis.read(); //文件裏是 d,當時write(100),寫進文件是 d 讀出來又變為 100 //read 只讀最後一個字節 /*System.out.println("read(): "+read); //read(): 100 char ch = (char)read; System.out.println("轉化:"+ch); //轉化:d */ byte[] bs = new byte[10]; int readLength = fis.read(bs); //返回讀到的實際字節長度;read每次讀完一個字節會自動偏移到下一個 String string = new String(bs); //這裏構造string,前面開辟多少空間,就算數組裏只有部分有數據,轉換的時候還是會按定義長度轉換,沒數據的當空格; //如果前面的是10 ,後面生成的string就會比是6的時候多一些空白,更長一點 System.out.println("readTobs: "+string+" readLength: "+readLength); //readTobs: 201703 readLength: 6 //數組長度為6 //readTobs: 201703 readLength: 6 //數組長度為10 String string1 = new String(bs,0,readLength); //消除上面存在的多余空格 System.out.println("readTobs: "+string1+" readLength: "+readLength); 技術分享圖片
int length = fis.read(bs,0,10); //參數一表示往哪個數組讀,參數二表示從數組的那個位置寫,第三個參數表示數組長度 String string2 = new String(bs,0,length); //構建字符串的時候指定從數組哪裏開始構建,構建多長; System.out.println("readTobs: "+string2+" readLength: "+length); fis.close(); //釋放資源 } } 技術分享圖片



public class IOTest3 {
public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("DiguiTest.java"); /* int read = 0; while((read = fis.read()) != -1){ //read 讀到文件尾會返回 -1 char ch = (char)read; System.out.print(ch); }*/

//一次讀取一個字節數組 //使用字節流不能處理文本中的中文,會出現亂碼;但是構建成String就不會出現亂碼 byte[] bytes = new byte[100]; int length = 0; while((length = fis.read(bytes)) != -1){ String string = new String(bytes,0,length); System.out.print(string); } fis.close(); } }






Java——IO類,字節流讀數據