gpt4 book ai didi

Java : How to read password from file?

转载 作者:行者123 更新时间:2023-12-02 06:13:10 24 4
gpt4 key购买 nike

我正在使用System.console()以便读取用户密码。

我的代码:

    Console console = System.console();
if (console == null) {
throw new RuntimeException("No console is available for input");
}

System.out.print("Enter the password: ");
String password = new String(console.readPassword());

当我直接运行它时,它工作正常(来自 Redhat )。

问题是当我尝试从文本文件读取密码时:

java -jar my_jar.jar < password.txt

我明白了:

No console is available for input.

如何解决?

最佳答案

此行为是预期的。引用自java.io.Console:

Whether a virtual machine has a console is dependent upon theunderlying platform and also upon the manner in which the virtualmachine is invoked. If the virtual machine is started from aninteractive command line without redirecting the standard input andoutput streams then its console will exist and will typically beconnected to the keyboard and display from which the virtual machinewas launched.

对于不使用Console的可能解决方案,您可以阅读此答案 Trying to read from the console in Java .

如果控制台存在,您可以继续使用它,如果不存在,则故障返回到 BufferedReader/Scanner

关于Java : How to read password from file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39347512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com