我正在处理的应用程序的加载网页速度非常慢。如果我运行以下代码它工作正常,但只是因为调用sleep
。如果我不睡觉,那么InputStream只是一堆空格,可能是由于它调用的应用程序。这有什么非黑客方式吗?
public class PublishTool extends Thread {
private URL publishUrl;
private String filerLocation;
public PublishTool() {
}
public PublishTool(String publishUrl, String filerLocation) throws NibException {
try {
this.publishUrl = new URL(publishUrl);
} catch (MalformedURLException e) {
throw new NibException("Publish Url :" + publishUrl + " is not valid. ");
}
this.filerLocation = filerLocation;
}
public void run() {
File filerFile = new File(filerLocation);
BufferedWriter writer = null;
try {
URLConnection conn = publishUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
writer = new BufferedWriter(new FileWriter(filerLocation));
Thread.sleep(1000l);
while (reader.ready()) {
writer.write(reader.readLine() + "\n");
}
} catch (MalformedURLException e) {
throw new IllegalStateException("Malformed URL for : " + publishUrl + " " + filerLocation, e);
} catch (IOException e) {
throw new IllegalStateException("IO Exception for : " + publishUrl + " " + filerLocation, e);
} catch (InterruptedException e) {
throw new IllegalStateException("Thread was interrupted early... publishing might have failed.");
} catch (NibException e) {
throw new IllegalStateException("Publishing File Copy failed : " + filerLocation + ".bak" + " to " + filerLocation);
} finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:4)
不要使用reader.ready()。只需调用readLine()并让readLine()阻塞,直到数据准备就绪。数据的结尾通常会用空行发出信号。
如果它有用,我的网站上有几个代码示例:reading from a URL。
答案 1 :(得分:1)
首先,如果您发布了实际代码,将会很有帮助。
我猜这个问题是调用Reader.ready
。与InputStream.available
类似,如果已经有缓冲输入,则返回true
。如果需要等待套接字,它将返回false
。通常,您不需要ready
。使用readLine
,如果它返回null
(对于流的结尾),则跳出循环。