Java InputStream和Reader
阿新 • • 發佈:2017-09-26
all 不能 數據讀寫 抽象基類 sys stat 使用 pri code
1. 字節流和字符流的區別:
字節流操作的數據單元是8位的字節,而字符流操作的數據單元是16位的字符。
2. 節點流和處理流的區別:
可以從/向一個特定的IO設備(如磁盤、網絡)讀、寫數據的流,稱為節點流,也被稱為低級流。
處理流則用於對一個已經存在的流進行連接或封裝,通過封裝後的流實現數據讀寫功能。
3. InputStream 和 Reader
InputStream 和 Reader 是所有輸入流的抽象基類,本身不能創建實例或執行輸入,但成為所有輸入流的模板,它們的方法是所有輸入流都可使用的方法。
InputStream包含如下方法:
//從輸入流種讀取單個字節,返回所讀取的字節數據int read(); //從輸入流種最多讀取b.length個字節的數據,並存儲在字節數組b種,返回實際讀取的字節數 int read(byte b[]); //從輸入流中最多讀取len個字符的數據,並將其存儲在字符數組buff中,並不是從數組起點開始,而是從off位置開始 int read(byte b[], int off, int len)
Reader包含如下方法:
//從輸入流中讀取單個字符,返回所讀取的字符數據 int read(); //從輸入流中最多讀取cbuf.length個字符數據,並存儲在cbuf中,返回實際讀取的字符數 int read(char cbuf[]);//從輸入流中最多讀取cbuf.length個字符數據,並存儲在cbuf中,從off開始存儲,返回實際讀取的字符數 int read(char cbuf[], int off, int len);
InputStream和Reader是抽象基類,本身不能創建實例,但它們分別有一個用於讀取文件的輸入流: FileInputStream, FileReader
public class FileInputStreamTest { public static void main(String[] args) { InputStream fis = null;try { fis = new FileInputStream("D:/rding/testfile2/file.txt"); byte[] bbuf = new byte[1024]; int hasRead = 0; while ((hasRead = fis.read(bbuf)) > 0) { System.out.println(new String(bbuf, 0, hasRead)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
public class FileReaderTest { public static void main(String[] args) { Reader fr = null; try { fr = new FileReader("D:/rding/testfile2/file.txt"); char[] cbuf = new char[32]; int hasRead = 0; while ((hasRead = fr.read(cbuf)) > 0) { System.out.print(new String(cbuf, 0, hasRead)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Java InputStream和Reader