• Post Reply Bookmark Topic Watch Topic
  • New Topic

File Listener?  RSS feed

 
Terrence White
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible for me to write code that will execute as soon as a file is placed into a particular directory?
I want to avoid writing code that will loop over and over again, checking for the existence of the file.
Does Java have listeners that could tell me when a file has been sent to me?
Thanks
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't believe so. Since a file is on a file system, and java doesn't have something like that. You can do polling by scan the directory periodically, (5 sec, 10 sec, etc).
 
Terrence White
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The read() method of InputStream blocks until input data is available.
How can I set up this condition on a file?
Will a 0 byte file do?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean, you want to intentionally force a stream to block, e.g. for testing purposes maybe? A 0-byte file won't do. The reader will simply return a -1 to indicate there are no [further] bytes to read. You might try creating a file, writing to it, and leaving it open for an extended period of time (Thread.sleep(someTime)). You'd have to do this in a separate thread from the thread you're reading with. If it doesn't work (I'm not 100% sure all file systems will let you open a FileInputStream on a file which is still being written to) then forget about files, and try using a PipedInputStream/PipedOutputStream combintion, or a Socket. Either way, you need different threads for the reader and writer, and to guarantee observable blocking you'll want to insert some Thread.sleep() calls into the writing thread.
Blocking may well occur spontaneously for various reasons. Try letting your hard drive become badly fragmented over time, and then try to read many different files at different parts of the disk - you'll probably experience quite a few delays. But if you're trying to
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!