如何将DataInputStream转换为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
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); } } }
这就是你想要的。
您可以使用commons-io IOUtils.toString(dataConnection.getInputStream(), encoding)
来实现您的目标。
DataInputStream
不用于您想要的 – 即您希望将网站内容作为String
读取。
如果要从通用URL(例如www.google.com
)读取数据,则可能根本不想使用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"; }