Is this supposed to be a
Java question?
In any event, that kind of stuff is normally handled by the lower levels of the I/O services. In C/C++, there are multiple solutions, depending on how much direct control of the process/vs. OS control/ language-supported control you want.
The secret of how to be miserable is to constantly expect things are going to happen the way that they are "supposed" to happen.
You can have faith, which carries the understanding that you may be disappointed. Then there's being a willfully-blind idiot, which virtually guarantees it.