How to convert the DataInputStream to the String in Java?

后端 未结 3 1215
旧巷少年郎
旧巷少年郎 2020-12-19 00:14

I want to ask a question about Java. I have use the URLConnection in Java to retrieve the DataInputStream. and I want to convert the DataInputStream into a String variable i

3条回答
  •  有刺的猬
    2020-12-19 01:06

    import java.net.*;
    import java.io.*;
    
    class ConnectionTest {
        public static void main(String[] args) {
            try {
                URL google = new URL("http://www.google.com/");
                URLConnection googleConnection = google.openConnection();
                DataInputStream dis = new DataInputStream(googleConnection.getInputStream());
                StringBuffer inputLine = new StringBuffer();
                String tmp; 
                while ((tmp = dis.readLine()) != null) {
                    inputLine.append(tmp);
                    System.out.println(tmp);
                }
                //use inputLine.toString(); here it would have whole source
                dis.close();
            } catch (MalformedURLException me) {
                System.out.println("MalformedURLException: " + me);
            } catch (IOException ioe) {
                System.out.println("IOException: " + ioe);
            }
        }
    }  
    

    This is what you want.

提交回复
热议问题