關於IO流的一些理解

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/wq1134302142/article/details/52294810


IO流: 主要分爲字節流和字符流.
字節流: 
|--- InputStream(字節輸入流)
通過API的查詢,可以得知,InputStream是一個抽象類;這個抽象類就表示字節輸入流的所有類的超類,也即父類.
但是如何去讀入字節呢,InputStream中的提供了一個read()方法,但是也是抽象的
這就意味着其子類都必須重寫read()方法.
我們舉個其子類的例子吧:FileInputStream
<span style="font-family:Times New Roman;"><span style="white-space:pre">	</span><span style="white-space:pre">	</span>public int read() throws IOException {
     <span style="white-space:pre">	</span>   Object traceContext = IoTrace.fileReadBegin(path);
      <span style="white-space:pre">	</span>  int b = 0;
       <span style="white-space:pre">	</span> try {
          <span style="white-space:pre">	</span>  b = read0();
        <span style="white-space:pre">	</span>} finally {
        <span style="white-space:pre">	</span>    IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);
       <span style="white-space:pre">	</span> }
     <span style="white-space:pre">	</span>   return b;
   <span style="white-space:pre">	</span> }

 <span style="white-space:pre">	</span>   private native int read0() throws IOException;</span>
通過分析源碼:我們知道FileInputStream底層是重寫了InputStream中的read()方法的,但是爲了可以直接調用
通過調用本地的read0()方法,FileInputStream就可以直接使用read()方法.

|---OutputStream(字節輸出流)
同樣的, OutputStream也是一個抽象的類,這個抽象類就表示字節輸出流的所有類的父類
與上面對應的也有個FileOutputStream;
但是FileOutputStream在創建對象時,不需要有指定的文本文件,
FileOutputStream fos = new FileOutputStream("test.txt",true);
fos.write(92);
fos.write(87);
fos.close();
就會自動在當前目錄下創建一個test.txt文件.
然後如果想繼續寫入,可以在傳入的參數里加上一個true;
最後記住關流;

字符流:
|----Readr(字符輸入流)
Reader作爲所有字符輸入流的父類,想必跟上面一下也是一個抽象類
Reader有個子類是FileReader;與FileInputStream相似.也是同樣的必須一個文本文件存在才能讀取裏面的
字符;
<span style="font-size: 18px;">	</span><span style="font-size:14px;">public static void main(String[] args) throws IOException {
		FileReader fr = new FileReader("xxx.txt");
		int c;
		
		while((c = fr.read()) != -1) {	   //通過項目默認的碼錶一次讀取一個字符
			System.out.print((char)c);<span style="white-space: pre;">	</span>//類型強轉
		}
		
		fr.close();
	}</span>

|----Writer(字符輸出流)
Writer作爲所有字符輸出流的父類,也是一個抽象類
Writer有個子類是FileWtriter;與FileOutputStream相似.但是和FileOutputStream有一點不同的是它在繼續寫入的時候
不需要再傳入參數中加上一個true,下面我們來看代碼
FileWriter fw = new FileWriter("test1.txt"); //創建一個字符輸出流對象 關聯test1.txt文件
fw.write("hello,world");
fw.write("你好,中國");
fw.close();


     


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章