有没有办法确定Java System.in是否是“交互式的"?

编程入门 行业动态 更新时间:2024-10-23 22:31:41
本文介绍了有没有办法确定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是否是“交互式的"?

本文发布于:2023-11-10 01:00:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   Java   quot   System

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!