JavaIO輸入輸出流的總結
阿新 • • 發佈:2019-02-07
IO流按流向可分兩類:
輸入流:InputStream /Reader。好比是一根水管,裡面有擠滿了的位元組或者字元單位。隱士指標記錄從哪個水滴開始讀取。 讀
輸出流:OutpStream/Writer。 也是一個水管,只是裡面沒有任何水滴,當向水管里加水的時候,才開始注入水滴。寫
提高效能:1.加緩衝 2處理流
InputStream /Reader:本身是抽象類,不能建立例項有方法 read() read(byte [] b) read(byte [] b,int off,int len)
FileInputStream FileReader 節點流。跟檔案聯絡在一起。
位元組可以處理任何資料型別,字元要比位元組能處理的型別要少。通常在處理文字時優先使用字元流,其他的用位元組流 在讀寫檔案需要對內容按行處理,比如比較特定字元,處理某一行資料的時候一般會選擇字元流。 只是讀寫檔案,和檔案內容無關的,一般選擇位元組流。
java只提供了將位元組流轉換為字元流的方法
把經常讀取文字的輸入流寫成BufferedReader
1.讀取使用者螢幕的輸入
public class FileInputStreamTest { public static void main(String[] args) throws IOExceptio try ( //將輸入流InpustStream 轉化為Reader物件 轉成字元輸入流InputStreamReader reader = new InputStreamRe //將普通的reader包裝成BufferReader的UBufferedReader br = new BufferedReader(reader);){ String line = null; while ((line=br.readLine())!=null){ if(line.equals("exit")){ System.exit(1);} System.out.print("輸出內容:"+line); } } catch (IOException i) { i.printStackTrace();} } }
2:向硬盤裡寫資料
try (FileWriter fw = new FileWriter("d:\\poem.txt")) { fw.write("錦瑟-李商隱\r\n");fw.write("莊生曉夢");} catch (IOException e) { e.printStackTrace();} }
3.讀取檔案資料
public class HelloJava { public static void main(String[] args){ try { FileWriter fileWriter = new FileWriter("test.txt"); //寫入資料到記憶體裡 fileWriter.write("adadada"); //重新整理流 fileWriter.flush(); fileWriter.close();//關閉流 }catch (IOException e) { e.printStackTrace(); } } }
try { FileReader fr = new FileReader("d:\\poem.txt"); char[] buf = new char[20]; int num = fr.read(buf);System.out.println("num" + num + new String(buf));} catch (FileNotFoundException e) { e.printStackTrace();} catch (IOException e) { e.printStackTrace();}