How to convert the DataInputStream to the String in Java?

后端 未结 3 1232
旧巷少年郎
旧巷少年郎 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: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";
    }
    

提交回复
热议问题