How to convert the DataInputStream to the String in Java?

后端 未结 3 1216
旧巷少年郎
旧巷少年郎 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 00:47

    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.

    0 讨论(0)
  • 2020-12-19 00:52

    If you want to read data from a generic URL (such as www.google.com), you probably don't want to use a DataInputStream at all. Instead, create a BufferedReader and read line by line with the readLine() method. Use the URLConnection.getContentType() field to find out the content's charset (you will need this in order to create your reader properly).

    Example:

    URL data = new URL("http://google.com");
    URLConnection dataConnection = data.openConnection();
    
    // Find out charset, default to ISO-8859-1 if unknown
    String charset = "ISO-8859-1";
    String contentType = dataConnection.getContentType();
    if (contentType != null) {
        int pos = contentType.indexOf("charset=");
        if (pos != -1) {
            charset = contentType.substring(pos + "charset=".length());
        }
    }
    
    // Create reader and read string data
    BufferedReader r = new BufferedReader(
            new InputStreamReader(dataConnection.getInputStream(), charset));
    String content = "";
    String line;
    while ((line = r.readLine()) != null) {
        content += line + "\n";
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题