一次读取输入流
我开发了一个 j2me 应用程序,通过套接字连接到我的虚拟主机服务器。我使用自己的扩展 lineReader 类读取来自服务器的响应,该类扩展了基本的 InputStreamReader。如果服务器发送 5 行回复,则逐行读取服务器回复的语法为:
line=input.readLine();
line = line + "\n" + input.readLine();
line = line + "\n" + input.readLine();
line = line + "\n" + input.readLine();
line = line + "\n" + input.readLine();
在这种情况下,我可以编写此语法,因为我知道回复的数量是固定的。但是如果我不知道行数,并且想一次读取整个 inputStream,我应该如何修改当前的 readLine() 函数。这是该函数的代码:
public String readLine() throws IOException {
StringBuffer sb = new StringBuffer();
int c;
while ((c = read()) > 0 && c != '\n' && c != '\r' && c != -1) {
sb.append((char)c);
}
//By now, buf is empty.
if (c == '\r') {
//Dos, or Mac line ending?
c = super.read();
if (c != '\n' && c != -1) {
//Push it back into the 'buffer'
buf = (char) c;
readAhead = true;
}
}
return sb.toString();
}
I have developed a j2me application that connects to my webhosting server through sockets. I read responses from the server using my own extended lineReader class that extends the basic InputStreamReader. If the server sends 5 lines of replies, the syntax to read the server replies line by line is:
line=input.readLine();
line = line + "\n" + input.readLine();
line = line + "\n" + input.readLine();
line = line + "\n" + input.readLine();
line = line + "\n" + input.readLine();
In this case, i can write this syntax because i know that there is a fixed number of replies. But if I dont know the number of lines, and want to read the whole inputStream at once, how should I modify the current readLine()
function. Here's the code for the function:
public String readLine() throws IOException {
StringBuffer sb = new StringBuffer();
int c;
while ((c = read()) > 0 && c != '\n' && c != '\r' && c != -1) {
sb.append((char)c);
}
//By now, buf is empty.
if (c == '\r') {
//Dos, or Mac line ending?
c = super.read();
if (c != '\n' && c != -1) {
//Push it back into the 'buffer'
buf = (char) c;
readAhead = true;
}
}
return sb.toString();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Apache Commons 怎么样 IOUtils.readLines()?
或者,如果您只想要单个字符串,请使用 IOUtiles.toString()。
[更新]根据关于 J2ME 上可用的评论,我承认我错过了这个条件,但是 IOUtils 源代码 的依赖关系很小,因此也许可以直接使用代码。
What about Apache Commons IOUtils.readLines()?
Or if you just want a single string use IOUtiles.toString().
[update] Per the comment about this being avaible on J2ME, I admit I missed that condition however, the IOUtils source is pretty light on dependencies, so perhaps the code could be used directly.
如果我理解正确的话,您可以使用一个简单的循环:
在循环中添加一个计数器,如果您的计数器 = 0,则返回 null:
If I understand you correctly, You can use a simple loop:
Add a counter in your loop, and if your counter = 0, return null:
专门用于网络服务器!
Specifically for web server !