首先請查看一下JavaAPI,能夠看到InputStream讀取流有三個方法,分別爲read(),read(byte[] b),read(byte[] b, int off, int len)。其中read()方法是一次讀取一個字節,鬼都知道效率是很是低的。因此最好是使用後面兩個方法。java
例如如下代碼:程序員
Java代碼
編程
- /**
- * 讀取流
- *
- * @param inStream
- * @return 字節數組
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
咱們來測試一下:數組
Java代碼
網絡
- public static void main(String[] args) {
- try {
- File file = new File("C:\\ceshi.txt");
- FileInputStream fin = new FileInputStream(file);
- byte[] filebt = readStream(fin);
- System.out.println(filebt.length);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
後臺會打印這個文本的字節大小。看起來,這個是沒有問題的。socket
關於InputStream類的available()方法
這個方法的意思是返回此輸入流下一個方法調用能夠不受阻塞地今後輸入流讀取(或跳過)的估計字節數。爲何須要這個方法?由於在一些網絡應用中,數據流並非一次性就能傳遞的,若是咱們仍是像上面那樣去將這個流轉換,會出問題的。咱們來作一個例子,這是一個Socket編程的簡單例子,具體Socket內容我會在後面文章中解釋的。工具
首先編寫兩個類,一個用戶初始化Socket服務,而且處理每一個請求都有新的線程去處理,代碼以下:測試
Java代碼
this
- package com.service;
- import java.net.*;
- public class DstService {
- public static void main(String[] args) {
- try {
- // 啓動監聽端口 8001
- ServerSocket ss = new ServerSocket(8001);
- boolean bRunning = true;
- while (bRunning) {
- // 接收請求
- Socket s = ss.accept();
- // 將請求指定一個線程去執行
- new Thread(new DstServiceImpl(s)).start();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
那麼處理類咱們也來看一下:.net
Java代碼 
- package com.service;
- import java.io.*;
- import java.net.*;
- import com.util.*;
- public class DstServiceImpl implements Runnable {
- Socket socket = null;
- public DstServiceImpl(Socket s) {
- this.socket = s;
- }
- public void run() {
- try {
- InputStream ips = socket.getInputStream();
- OutputStream ops = socket.getOutputStream();
- while (true) {
- byte[] bt = StreamTool.readStream(ips);
- String str = new String(bt);
- System.out.println("主機收到信息:" + str);
- String restr = "你好,主機已經收到信息!";
- ops.write(restr.getBytes());
- ops.flush();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
至於工具類,我就直接給代碼了:
Java代碼 
- package com.util;
- import java.io.*;
- public class StreamTool {
- public static void main(String[] args) {
- try {
- File file = new File("C:\\ceshi.txt");
- FileInputStream fin = new FileInputStream(file);
- byte[] filebt = readStream(fin);
- System.out.println(filebt.length);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * @功能 讀取流
- * @param inStream
- * @return 字節數組
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
你能夠直接運行這個類,會看到流被轉換的效果。
咱們來寫一個Socket客戶端測試一下:
Java代碼 
- package com.client;
- import java.io.*;
- import java.net.*;
- import com.util.*;
- public class DstClient {
- public static void main(String[] args) {
- try {
- Socket socket = new Socket("127.0.0.1", 8001);
- // 開啓保持活動狀態的套接字
- socket.setKeepAlive(true);
- // 設置讀取超時時間
- socket.setSoTimeout(30 * 1000);
- OutputStream ops = socket.getOutputStream();
- String mess = "你好,我是崔素強!";
- ops.write(mess.getBytes());
- InputStream ips = socket.getInputStream();
- byte[] rebyte = StreamTool.readStream(ips);
- String remess = new String(rebyte);
- System.out.println("收到主機消息:" + remess);
- socket.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
先運行DstService,而後運行客戶端,看效果。會發現,控制檯沒有任何輸出。通過調試發現,由於請求死在了
Java代碼 
- while ((len = inStream.read(buffer)) != -1) {
這行代碼上面。這就是在網絡應用中會形成的後果。那麼如何解決呢?有的人給出了以下代碼:
Java代碼 
- int count = in.available();
- byte[] b = new byte[count];
- in.read(b);
但是在進行網絡操做時每每出錯,由於你調用available()方法時,對發發送的數據可能尚未到達,你獲得的count是0。須要作以下修改,是咱們的讀取流方法改爲以下:
Java代碼 
- /**
- * @功能 讀取流
- * @param inStream
- * @return 字節數組
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception {
- int count = 0;
- while (count == 0) {
- count = inStream.available();
- }
- byte[] b = new byte[count];
- inStream.read(b);
- return b;
- }
下面你在運行,會看到服務端和客戶端都收到了消息。
關於InputStream.read(byte[] b)和InputStream.read(byte[] b,int off,int len)這兩個方法都是用來從流裏讀取多個字節的,有經驗的程序員就會發現,這兩個方法常常 讀取不到本身想要讀取的個數的字節。好比第一個方法,程序員每每但願程序能讀取到b.length個字節,而實際狀況是,系統每每讀取不了這麼多。仔細閱讀Java的API說明就發現了,這個方法 並不保證能讀取這麼多個字節,它只能保證最多讀取這麼多個字節(最少1個)。所以,若是要讓程序讀取count個字節,最好用如下代碼:
Java代碼 
- int count = 100;
- byte[] b = new byte[count];
- int readCount = 0; // 已經成功讀取的字節的個數
- while (readCount < count) {
- readCount += inStream.read(b, readCount, count - readCount);
- }
這樣就能保證讀取100個字節,除非中途遇到IO異常或者到了數據流的結尾狀況!