我正在尝试阅读网址的第一行。 然后我想在代码中稍后使用它作为字符串。 有人可以帮帮我吗? 我已经尝试了
public static String main(String[] args) {
try {
URL url = new URL("myurlhere");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
return line;
}
in.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
return null;
}
我只是无法从中获取字符串。
答案 0 :(得分:1)
您可以考虑将jsoup用于您的目的:
try {
Document doc = Jsoup.connect("http://popofibo.com/pop/swaying-views-of-our-past/").get();
Elements paragraphs = doc.select("p");
for(Element p : paragraphs) {
System.out.println(p.text());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出:
确实很难争论人类文明进化的主流思想......
答案 1 :(得分:0)
如果您想使用URL读取互联网上的文件,您应该使用URLConnection
这是一个简单的例子:
String string = "";
try {
URLConnection connection = new URL(
"http://myurl.org/mypath/myfile")
.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
while (scanner.hasNext()) {
string += scanner.next() + " ";
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
// Do something with the string.