如何将DataInputStream转换为Java中的String?

Que*_*ons 10 java string

我想问一个关于Java的问题.我在Java中使用URLConnection来检索DataInputStream.我想将DataInputStream转换为Java中的String变量.我该怎么办?谁能帮我.谢谢.

以下是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

Jig*_*shi 10

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);
        }
    }
}  
Run Code Online (Sandbox Code Playgroud)

这就是你想要的.


Boz*_*zho 7

你可以使用commons-io IOUtils.toString(dataConnection.getInputStream(), encoding)来实现你的目标.

DataInputStream不是用于你想要的东西 - 即你想要阅读网站的内容String.


Gro*_*uez 7

如果要从通用URL(例如www.google.com)中读取数据,则可能根本不想使用a DataInputStream.而是BufferedReader使用该readLine()方法逐行创建和读取.使用该URLConnection.getContentType()字段查找内容的字符集(您需要这样才能正确创建您的阅读器).

例:

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";
}
Run Code Online (Sandbox Code Playgroud)