Read input stream immediately

I developed a j2me application that connects to my web hosting server through sockets. I read responses from the server using my own extended lineReader class, which extends the base InputStreamReader. If the server sends 5 response lines, the syntax for reading server responses is line by line:

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 answers. But if I do not know the number of lines and want to read the entire input stream immediately, how can I change the current readLine() function. Here is 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(); } 
+7
source share
3 answers

What about Apache Commons IOUtils.readLines () ?

Get the contents of InputStream as a list of strings, one record per line, using the default encoding for the platform.

Or, if you just want one line to use IOUtiles.toString () .

Get the contents of an InputStream as a String using standard platform character encoding.

[update] You can learn about J2ME in a comment about this, I admit that I skipped this condition, however the source of IOUtils is pretty simple in dependencies, so maybe the code can be used directly.

+5
source

If you understand correctly, you can use a simple loop:

 StringBuffer sb = new StringBuffer(); String s; while ((s = input.readLine()) != null) sb.append(s); 

Add a counter to your loop, and if your counter = 0, return null:

 int counter = 0; while ((c = read()) > 0 && c != '\n' && c != '\r' && c != -1) { sb.append((char)c); counter++; } if (counter == 0) return null; 
+1
source

In particular, for the web server!

 String temp; StringBuffer sb = new StringBuffer(); while (!(temp = input.readLine()).equals("")){ sb.append(line); } 
0
source

All Articles