字節流一次讀取一行數據?
觀察圖可發現是可以實現字節流一次讀取一行的。
測試1:無中文
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("G:\\a.txt")));
String str = null;
while ((str = br.readLine()) != null){
System.out.println(str);
}
/*
結果:一共讀了3次,每次讀取一行
Hello World!
Hello Java!
Hello CSDN!
*/
測試2:有中文
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("G:\\a.txt"),"GBK"));
String str = null;
while ((str = br.readLine()) != null){
System.out.println(str);
}
/*
結果:使用了轉換流的特徵,對編碼進行轉換
Hello World!
Hello 程序猿!
Hello Java!
Hello CSDN!
*/
多個流結合,可以使用不同流的特性來解決問題。
例子:寫一個服務端,使用網頁進行訪問服務端,服務端實現會寫數據。
分析:GET /Demo/web/index.html HTTP/1.1
請求頭是我們最關注的信息,我們來獲取請求頭信息,用於鎖定頁面在本地的位置,因爲ServerSocket服務端裏面的getInputStream();方法返回的是一個字節流,所以我們使用上面說到的,字節流一次讀取一行的方式,只讀取第一行請求頭信息即可。
/*
注意:如果是B/S交互的話,不要關閉服務器,以爲瀏覽器還會隨之帶着一些其他的請求
如果你關閉了,會報一個異常,因爲還有其他請求,但是你已經關閉了服務器,所以就會報異常。
需求:請編寫模擬B/S服務器案例。
*/
//HTML代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>測試成功!</h1>
<img src="imgs/a.png">
</body>
</html>
//java服務端代碼
public class BS {
public static void main(String[] args)throws Exception {
ServerSocket ss = new ServerSocket(8080);
while (true){
//等待客戶端發送請求
Socket accept = ss.accept();
//創建服務器字符輸入流對象
InputStream is = accept.getInputStream();
//創建BufferedReader對象並傳入轉換流將inputStream丟進去
// 這樣就能夠達到一次讀取一行的效果
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = br.readLine();
//GET /Demo/web/index.html HTTP/1.1這是原有的路徑名
//根據" "切割字符串剛好可以得到 /Demo/web/index.html
//處理字符串,得到路徑名
String[] split = s.split(" ");
String str = split[1];
//然後在去掉前面的正斜槓就行了
String path = str.substring(1);
//創建FileInputStream對象讀取本地頁面
FileInputStream fis = new FileInputStream(path);
//調用getOutputStream,往客戶端響應頁面
OutputStream os = accept.getOutputStream();
//寫協議信息
os.write("HTTP/1.1 200 OK\r\n".getBytes());//響應行
os.write("Content-Type:text/html\r\n".getBytes());//響應頭
os.write("\r\n".getBytes());
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1){
//讀一次網頁內容,往客戶端寫一次網頁內容
os.write(bytes,0,len);
}
//關流
os.close();
fis.close();
br.close();
is.close();
accept.close();
//ss.close(); 服務器一般不需要關閉,如果關閉會產生一個異常,上面有講解
}
}
}
測試結果必然是成功的:這是網頁上顯示的數據。