2013-04-13 60 views
0

我目前有一個連接建立到一些中間件,通過它我發送SQL查詢到數據庫。Android/Java - 將DataInputStream轉換爲字符串

我在將DataInputStream轉換爲可用格式(不管它是否是字符串)時遇到了一些麻煩。我看着another StackOverflow question,但是因爲使用

in.readLine(); 

是「過時」,這意味着什麼,這並沒有解決我的問題。我需要能夠讀取我的中間件的響應。

private class NetworkTask extends AsyncTask<String, Void, Integer> 
{ 
    protected Integer doInBackground(String... params) 
    { 
     Message message = networkHandler.obtainMessage(); 

     String ip = "example ip"; 
     int port = 1234; 

     try 
     { 
      InetAddress serverAddr = InetAddress.getByName(ip); 
      Log.d("EventBooker", "C: Connecting..."); 
      Socket socket = new Socket(serverAddr, port);    

      DataInputStream in = new DataInputStream(socket.getInputStream()); 


      try 
      { 
       Log.d("EventBooker", "C: Connected. Sending command."); 
       PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 
       out.println(params[0]); 
       networkHandler.sendMessage(message); 
       Log.d("EventBooker", "C: Sent."); 
      } 
      catch (Exception e) 
      { 
       Log.e("EventBooker", "S: Error", e); 
      } 
      Log.d("EventBooker", "C: Reading..."); 



      Log.d("EventBooker", "C: Response read, closing."); 
      socket.close(); 
      Log.d("Eventbooker", "C: Closed."); 
     } 
     catch (Exception e) 
     { 
      Log.e("EventBooker", "C: Error", e); 
     } 
     return 1; 
    } 
} 
+0

試試這個:http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string?rq=1 – Rotemmiz

+0

@Rotemmiz - 我也嘗試過,也沒有運氣。 IOUtils不能在Android中使用嗎? Eclipse不喜歡使用IOUtils。 –

回答

2

將您DataInputStreamBufferedReaderStream這樣的:

BufferedReader d = new BufferedReader(new InputStreamReader(in)); 

然後,你希望得到您的實際String,要做到這一點,你做這樣的事情:

StringBuffer sb = new StringBuffer(); 
String s = ""; 

while((s = d.readLine()) != null) { 
    sb.append(s); 
} 

String data = sb.toString(); 

//Use data for w/e 

簡單,簡單!

我們不只是將它附加到已經存在的字符串的原因是Java Strings是不可變的,因此每次重新創建String對象時都會產生性能問題。所以StringBuffer

+0

我以前試過這個,但是我得到了這個迴應:1)字符串不能解析爲變量。 2)令牌「s」上的語法錯誤,請刪除此令牌。 3)類型不匹配:不能從字符串轉換爲布爾值。 4)類型不匹配:無法從布爾型轉換爲字符串 –

+0

此外,Eclipse提供的唯一快速修復方法是在我們已有的「!= null」之後添加另一個「!= null」。 –

+0

Omg對不起...檢查修訂版本,它不是另一個字符串...我的壞,有一杯酒... –