java 键盘输入

boyley 2013-12-18 11:01:33
大家好,小弟问一个关于流的问题,问题如下,异常大家就忽略吧,代码形式如下:

public String func() {
InputStream is = System.in; // 指向键盘
InputStreamReader isr = new InputStreamReader(is);
reader = new BufferedReader(isr);
String line = null;
line = reader.readLine();
return line
}


外部调用此方法时必须要等到键盘输入才能返回数据,但这是一个阻塞时的线程,可是我的需求是外部调用此方法时必须在30秒内返回数据,如键盘没有输入,就返回一个外部没有输入的错误信息,如果在30秒内键盘输入了信息就立即返回输入的数据,请问我该怎么做呢
...全文
233 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
boyley 2013-12-18
  • 打赏
  • 举报
回复
引用 4 楼 KennycdjjMicr 的回复:
很简单的代码就可以做出来

public String parseMagcard(Charset charset) {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		long startTime = System.currentTimeMillis();
		String line = null;
		try {
			while ((System.currentTimeMillis() - startTime) < time * 1000
					&& !in.ready()) {
			}
			if (in.ready()) {

				line = in.readLine();
			} else {
				// System.out.println("You did not enter data");
				line = "-1";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return line;

	}
这个大哥做对了,可以用
boyley 2013-12-18
  • 打赏
  • 举报
回复
引用 2 楼 u013028373 的回复:
我模拟一个:

public class Test2 {	
	static  String a;	
	public static void main(String[] args) throws InterruptedException {
		T t = new T();
		t.setDaemon(true);
		t.start();
		System.out.print("等待用户输入:");
		Thread.sleep(3000);
		if(a==null){
			System.out.println("no");
		}else{
			System.out.println(a);
		}
		System.out.println("over");	
	}

}
class T extends Thread{
	@Override
	public void run() {
		Test2.a = new Scanner(System.in).nextLine();
	}
}
大哥你这个不行的,如果用户在指定的时间输入了数据会立即返回,不用等待了
KennycdjjMicr 2013-12-18
  • 打赏
  • 举报
回复
很简单的代码就可以做出来

public String parseMagcard(Charset charset) {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		long startTime = System.currentTimeMillis();
		String line = null;
		try {
			while ((System.currentTimeMillis() - startTime) < time * 1000
					&& !in.ready()) {
			}
			if (in.ready()) {

				line = in.readLine();
			} else {
				// System.out.println("You did not enter data");
				line = "-1";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return line;

	}
小陈杰帝 2013-12-18
  • 打赏
  • 举报
回复
我模拟一个:

public class Test2 {	
	static  String a;	
	public static void main(String[] args) throws InterruptedException {
		T t = new T();
		t.setDaemon(true);
		t.start();
		System.out.print("等待用户输入:");
		Thread.sleep(3000);
		if(a==null){
			System.out.println("no");
		}else{
			System.out.println(a);
		}
		System.out.println("over");	
	}

}
class T extends Thread{
	@Override
	public void run() {
		Test2.a = new Scanner(System.in).nextLine();
	}
}
小陈杰帝 2013-12-18
  • 打赏
  • 举报
回复
多线程啊~~~~~新建一个线程读取用信息用,主线程柱塞获取信息

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧