[英]Input Stream & Input Stream Reader
try{
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char ch = (char) data;
result+=ch;
data = reader.read();
}
return result;
}catch(Exception e){
e.printStackTrace();
return null;
}
誰能解釋一下這段代碼的功能! 因為我不明白為什么我們在這里使用整數來存儲流值以及 while 循環在這里是如何工作的。
根據此處的 InputStreamReader 文檔, read()
返回一個整數值“讀取的字符,如果已到達流的末尾,則返回 -1”。 這意味着read()
讀取一個字符,如果返回值為 -1 則意味着我們已經到達流的末尾並且循環條件現在為假並退出。
此代碼逐個字符地讀入數據輸入流。
首先,您要設置輸入流:
try{
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
然后讀取數據的第一個字符:
int data = reader.read();
閱讀()傳回的字符讀取(如果讀取成功)或整數值-1(如果讀取不成功),這就是為什么它用作while循環的條件:
while(data != -1){ // while read returns something other than FAIL (-1)
char ch = (char) data; // Convert the integer value read to a char
result+=ch; // Append the char to our result string
data = reader.read(); // read the next value
}
然后,其余代碼返回結果字符串(所有正確讀取的字符粘在一起)或捕獲異常。
return result;
}catch(Exception e){
e.printStackTrace();
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.