Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the DataInputStream to the String in Java?

Tags:

java

string

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 in Java. What should I do? Can anyone help me. thank you.

The following is my code:

URL data = new URL("http://google.com");
URLConnection dataConnection = data.openConnection();
DataInputStream dis = new DataInputStream(dataConnection.getInputStream());
String data_string;
// convent the DataInputStream to the String
like image 693
Questions Avatar asked Oct 06 '10 08:10

Questions


2 Answers

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.

like image 184
jmj Avatar answered Nov 03 '22 09:11

jmj


You can use commons-io IOUtils.toString(dataConnection.getInputStream(), encoding) in order to achieve your goal.

DataInputStream is not used for what you want - i.e. you want to read the content of a website as String.

like image 38
Bozho Avatar answered Nov 03 '22 09:11

Bozho