【发布时间】:2015-10-06 13:29:48
【问题描述】:
我已经查看了所有内容,但尚未找到解决方案。总而言之,我正在尝试从提供的 URL 中获取文本文件并将其读入字符串,以便我可以用它做其他事情。
具体的编译错误是:
/tmp/java_kWWEO5/Main.java:49: error: unreported exception IOException; must be caught or declared to be thrown String text = readUrlTextContent("http://textfiles.com/stories/antcrick.txt"); ^ 1 error
导致错误的代码,在main:
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
private static String readUrlTextContent(String url) throws IOException, MalformedURLException {
URL source = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(source.openStream()));
try {
StringBuilder builder = new StringBuilder();
String line = reader.readLine();
while (line != null) {
builder.append(line);
builder.append("\n");
line = reader.readLine();
}
return builder.toString();
} catch (MalformedURLException urlEx) {
urlEx.printStackTrace();
throw new RuntimeException("Malformed URL Exception", urlEx);
} catch (IOException ioEx) {
ioEx.printStackTrace();
throw new RuntimeException("IO Exception", ioEx);
} finally {
reader.close();
}
}
public static void main(String[] args) {
String text = readUrlTextContent("http://textfiles.com/stories/antcrick.txt");
System.out.println(text);
}
}
我可以做些什么来修改这个短程序,以便它最终编译和执行?
【问题讨论】:
-
你也可以
public static void main(String[] args) throws IOException