简体   繁体   中英

passing values of IO Process to another class in real time in java

I have a basic question for which I need a some clarification in it's use.
So if I have one class in Java say IOReadWrite.java , where I do some IO read/write. So that it may have an always connected loop something like:

while ((line = stream.readLine()) != null){
     //incoming data
}  

Now I have another class, call it FrontEnd.java where I am supposed to display the results coming in real time from IOReadWrite.java Class. Normally what is happening is that if I call the method of IO class, I can not get result unless the whole IO Operation is finished and I have to wait.

However what I want is to be able to get those results in real time, so that as soon as there is something on input Stream, I can get it in my FrontEnd Class to do whatever I want to do with it.

One idea I have come up with is using a static String variable in IOReadWrite.java and write a method which simply returns the value of this variable and I can poll this function from main class. But I'm pretty sure this is a very bad approach.

Can you suggest what is the proper way of getting such information in real time?

You can do this

FrontEnd frontEnd = 
while ((line = stream.readLine()) != null){
     //incoming data

     // notify immediately.
     frontEnd.displayLine(line);
}

What displayLine does depends on your implementation of that class. Can you give any more details of that the class does with the information?

Something it could do is

private final BlockingQueue<String> linesQueue = ...

public void displayLine(String line) {
     linesQueue.add(line);
}

// somewhere else, in another thread.
String line = linesQueue.take(); // wait for a line.

String line = linesQueue.poll(); // get the next or null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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