I’m attempting to read input events in Linux. I tried to use WatchService unusuccessfully and then migrated to Apache Commons IO, also unsuccessfully. I imagine that these character devices don’t generate filesystem events that either of these two mechanisms pick up?
import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
public class App
{
public static void main(String[] args) throws Exception
{
File file = new File("/dev/tty0");
FileOutputStream output = new FileOutputStream(file);
PrintStream stream = new PrintStream(output, true, StandardCharsets.UTF_8);
System.setOut(stream);
System.setErr(stream);
FileAlterationObserver observer = new FileAlterationObserver("/dev/input");
FileAlterationMonitor monitor = new FileAlterationMonitor(1000l);
FileAlterationListener listener = new FileAlterationListenerAdaptor()
{
@Override
public void onFileCreate(File file)
{
System.out.println(file);
try{Thread.sleep(2000);}catch(Exception e){}
System.exit(0);
}
@Override
public void onFileDelete(File file)
{
System.out.println(file);
try{Thread.sleep(2000);}catch(Exception e){}
System.exit(0);
}
@Override
public void onFileChange(File file)
{
System.out.println(file);
try{Thread.sleep(2000);}catch(Exception e){}
System.exit(0);
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}
This code generates no output onto /dev/tty0. My next step is to actually read from the character device /dev/input/js0 as suggested here. I’ve understood that the character device can be read in blocking or non-blocking mode. However, I’m unsure as to how to start. Does this involve opening/closing the stream periodically and some sort of polling interval? Does the stream remain open at all times and get placed and its subsequent operations get placed into a separate running thread?