如何在Java中将DataInputStream转换为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

回答:

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);

}

}

}

这就是你想要的。

以上是 如何在Java中将DataInputStream转换为String? 的全部内容, 来源链接: utcz.com/qa/425942.html

回到顶部