我应该如何阅读缓冲读卡器? [英] How should I read from a buffered reader?

查看:180
本文介绍了我应该如何阅读缓冲读卡器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下从缓冲读卡器中读取的示例:

I have the following example of reading from a buffered reader:

while ((inputLine = input.readLine()) != null) {
   System.out.println("I got a message from a client: " + inputLine);
}

循环中的代码 println (在这种情况下,输入)。在我的例子中,如果客户端应用程序向套接字写入内容,则循环中的代码(在服务器应用程序中)将被执行。

The code in the loop println will be executed whenever something appears in the buffered reader (input in this case). In my case, if a client-application writes something to the socket, the code in the loop (in the server-application) will be executed.

但我不这样做了解它是如何工作的。 inputLine = input.readLine()等待缓冲的阅读器中出现某些内容,当出现某些内容时,它会返回 true 并且循环中的代码被执行。但是当 null 可以返回时。

But I do not understand how it works. inputLine = input.readLine() waits until something appears in the buffered reader and when something appears there it returns true and the code in the loop is executed. But when null can be returned.

还有一个问题。上面的代码取自一个抛出异常的方法,我在Thread的run方法中使用了这个代码。当我在运行之前尝试将抛出异常时,编译器会抱怨:重写方法不会抛出异常。没有抛出异常我还有另一个来自编译器的抱怨:未报告的异常。那么,我该怎么办?

There is another question. The above code was taken from a method which throws Exception and I use this code in the run method of the Thread. And when I try to put throws Exception before the run the compiler complains: overridden method does not throw exception. Without the throws exception I have another complain from the compiler: unreported exception. So, what can I do?

推荐答案

当另一端的套接字关闭时,阅读器应该返回一个空字符串。这是您正在寻找的条件。要处理异常,请将读取循环包装在try / catch块中。

When the socket on the other end is closed, the reader should return a null string. This is the condition that you are looking for. To handle the exception, wrap the reading loop in a try/catch block.

 try {
   while ((inputLine = input.readLine()) != null) {
     System.out.println("I got a message from a client: " + inputLine);
   }
 }
 catch (IOException e) {
   System.err.println("Error: " + e);
 }

你可能会发现这个教程,很有帮助。

You might find this tutorial on reading/writing from/to a socket in Java, helpful.

这篇关于我应该如何阅读缓冲读卡器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆