• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to keep a stream open for multiple classes to access  RSS feed

 
Brian LaRue
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,

I hope I'm posting this to the right forum, please forgive me if I'm not. Here's my issue:

I'm a Java noob (also to programming in general) and trying to learn the language by creating my own text-based Gladiator game. It takes user input for levelups, types of strikes, weapon switches, character name, etc. I'm using an InputStreamReader piped into a BufferedReader to accept input from the console at runtime. However, I can't seem to figure out how to keep the stream open long enough so more than one class can use it at runtime.

I can get it to accept input the first time it's called, but when the second time comes around (which is in another class) I get an IOException that the stream is closed. I've tried to put the br.close() method at various parts in the program and it doesn't make any difference. It always throws the exception when the second call is made.

I'm not that familiar with algorithms and patterns, so if there's one that solves this problem please point me in the right direction.

How do I keep the stream open where it can be used by different classes of the program? Do I create thread for the stream, or do I have a class that keeps track of the stream and then passes its reference as needed?

TIA,

Brian
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you keep the stream open by not calling br.close(), so I'm not suite sure what you're trying to accomplish by placing br.close calls in your code.

Instead of trying to access the stream directly from various places in the code, I'd create a thread that keeps polling it, and stores everything it reads in a data structure, which can then be accessed by whichever code parts need to.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!