简体   繁体   English

为什么我可以在没有Eventlistener的情况下使用Java中的BufferedReader进行读取

[英]Why can I read with a BufferedReader in Java without Eventlistener

I am comfortable with actionscript. 我对动作脚本感到满意。 When I wantet to have network access for example in air, I coded the request and waited for the EventListener to kick in. 当我想在空中访问网络时,我对请求进行了编码,然后等待EventListener启动。

At the moment I'm doing a java tutorial with the following android code (wrapped in a try/catch): 目前,我正在使用以下android代码(包装在try / catch中)进行Java教程:

url = new URL("http://www.google.com");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream());
String line = '';
while((line = reader.readLine()) != null) {
     // do something with the line
}

I don't get how this works. 我不知道这是如何工作的。

Why is there no eventListener needed? 为什么不需要eventListener? If the code proceeds immidiately after the URL is requested, the URL may not been retrieved when the while-Construct kicks in. 如果在请求URL后立即执行代码,则在while-Construct启动时可能未检索到URL。

Is the app just paused in the meantime? 在此期间,应用程序是否刚刚暂停? If yes, is it possible to realise this with an eventlistner? 如果是,是否可以通过事件列表器实现?

Thank you for help! 谢谢你的帮助!

What happens is that the BufferedReader will request its underlying InputStream for data every time it is requested to provide data (when you call reader.readLine() or any other readXXX method on the BufferedReader ). 发生的情况是,每次请求提供数据时(当您在BufferedReader上调用reader.readLine()或任何其他readXXX方法时), BufferedReader都将请求其底层InputStream的数据。 It's thus the InputStream 's responsibility to provide it at that time - which might be possible or not (if the connection was closed, for instance). 因此, InputStream负责在那时提供它-可能是否可能(例如,如果连接已关闭)。

In this particular case, the InputStream provided by the URLConnection will either return data that was cached in a previous read request or request more data from the URL it's pointing to. 在这种特定情况下, URLConnection提供的InputStream将返回在先前的读取请求中缓存的数据,或者从其指向的URL请求更多数据。

As such, no actual data is read until you invoke readLine on the BufferedReader . 因此,在您调用BufferedReader上的readLine之前,不会读取任何实际数据。 You've just opened a connection to the server. 您刚刚打开了与服务器的连接。

Is the app just paused in the meantime? 在此期间,应用程序是否刚刚暂停?

Yes. 是。 The regular Java IO classes are synchronous. 常规Java IO类是同步的。 The call to readLine() will block until either it can return a line or there's an Exception. readLine()的调用将阻塞,直到可以返回一行或出现异常为止。

If yes, is it possible to realise this with an eventlistner? 如果是,是否可以通过事件列表器实现?

Yes, by using classes in the java.nio package . 是的,通过使用java.nio包中的java.nio But only with a somewhat lower-level interface. 但仅具有较低级别的接口。

In general, Java applications use multithreading instead of event qeueues to deal with such sitatuations. 通常,Java应用程序使用多线程而不是事件队列来处理这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM