The moose likes I/O and Streams and the fly likes Cant understand why... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Cant understand why..." Watch "Cant understand why..." New topic

Cant understand why...

Jessid Leon Velez Gutierrez

Joined: Dec 04, 2006
Posts: 22
Hello. I am sorry for asking this thing, but I cant understand why this code works the way it does. This is a segment of a program to read the serial port that I extracted from My question is about this while...cant understand how it works.

Thanks a lot!

public static class SerialReader implements Runnable {
InputStream in;

public Lector( InputStream in ) { = in;

public void run() {
byte[] buffer = new byte[1024];
int len = -1;
try {
while ( ( len = > -1 ) {
System.out.print(new String(buffer,0,len));
//System.out.println("La longitud del buffer es: " + len);
System.out.println("alguna cosa");
} catch ( IOException e ) {
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

Originally posted by Jessid Leon Velez Gutierrez:
I cant understand why this code works the way it does.

Maybe you could clue us in to what the code does. This code will not execute as a stand-alone program so we can't see for ourselves.
What do you expect the code to do and why does it not meet your expectations?

[How To Ask Questions On JavaRanch]
Jessid Leon Velez Gutierrez

Joined: Dec 04, 2006
Posts: 22
Hi. Thanks for the interest. What the program does is just read a serial port,and prints the characters you send to the PC in the command line. I was expecting that the while statement run only once and exited when len = -1, due to the lack of chars in the buffer, and when I sent new data, it didnt print it in the command line, but it never goes out the while...and that is what I cant understand well: why is that a never ending while. i think i havent understood well all this stuff of streams....i better begin to study again, jijiji

Thanks again!

English is not my native language. I hope I have not made a lot of mistakes, or at least the idea was transmitted
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15091

What is the InputStream? Is it a special kind of InputStream that reads data from a serial port?

Maybe the input stream never returns -1; maybe, if no data available, it just blocks until data is available. Look it up in the documentation of the serial port communications package that you're using.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Cant understand why...
It's not a secret anymore!