有没有办法确定Java System.in是否是“交互式的"? [英] Is there a way to determine if Java System.in is "interactive"?

查看:40
本文介绍了有没有办法确定Java System.in是否是“交互式的"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果输入是交互式的,即从控制台输入,我想打印一个命令提示符,例如>"

If the input is interactive, i.e. from the console, I want to print a command prompt e.g. ">"

但是如果重定向,例如从文件中删除,那么我不想提示.

But if it is redirected e.g. from a file, then I do not want to prompt.

System.in是一个抽象的InputStream,似乎对此没有任何方法.

System.in is an abstract InputStream which does not appear to have any method for this.

如果具体类型不同,也许可以使用instanceof?

Maybe you could use instanceof if the concrete type is different?

同样,如果System.out重定向到文件,我也不想提示

As well, if System.out is redirected to a file I also do not want to prompt

推荐答案

AFAIK,在纯Java中无法做到这一点,即使在JNI/JNA中也是如此.

AFAIK, there is no way to do this in pure Java, and even doing it in JNI / JNA would be complicated.

一种替代方法是使用JDK 1.6中引入的新控制台API.这使您可以尝试获取控制台的读取器/写入器.如果成功,则可以保证结果是交互式的……按照您的意思.

An alternative might be to use the new Console API introduced in JDK 1.6. This allows you to try to get a reader/writer for the console. If it succeeds, the result is guaranteed to be interactive ... in the sense that you mean.

第二种选择是检查用于启动应用程序的包装脚本中的常规工作,然后通过系统属性将信息传递给Java.例如,在GNU/Linux系统上,可以使用 tty(1)命令来判断stdin是否已连接到"tty"设备.

A second alternative would be to check do the legwork in the wrapper script that you use to launch your application, and pass the information to Java via the system properties. For instance, on a GNU/Linux system the tty(1) command can be used to tell if stdin is a connected to a "tty" device.

这篇关于有没有办法确定Java System.in是否是“交互式的"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆