// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

public class TimedRead2 {
    public String readLine(int ms) throws IOException {
        Timer t = new Timer();
        FileChannel fc = new FileInputStream(FileDescriptor.in).getChannel();
        ByteBuffer bb = ByteBuffer.allocate(80);
        String res = null;
        try {
            t.schedule(new InterruptMe(fc), ms);
            fc.read(bb);
            byte[] b = bb.array();
            int len = bb.position();
            while(len > 0 && (b[len-1] == '\r' || b[len-1] == '\n')) len--;
            res = new String(b, 0, len);
        } catch (AsynchronousCloseException e) {
            res = null;
        }
        t.cancel();
        return res;
    }
    public static void main(String[] args) throws Exception {
        TimedRead tr = new TimedRead();
        System.out.print("Enter something: ");
        String s = tr.readLine(5000);
        System.out.println("You entered: " + s);
        System.out.print("Enter something: ");
        String s2 = tr.readLine(5000);
        System.out.println("You entered: " + s2);
    }
}

class InterruptMe extends TimerTask {
    private Channel c;
    public InterruptMe(Channel c) {
        this.c = c;
    }
    public void run() {
        try {
            c.close();
        } catch (IOException e) {
            // ignore
        }
    }
}
