Eclipse IDE 中的 java.io.Console 支持

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/104254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:20:14  来源:igfitidea点击:

java.io.Console support in Eclipse IDE

javaeclipseconsolejava-io

提问by Ross

I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the java.io.Consoleclass to manage output and, more importantly, user input.

我使用 Eclipse IDE 来开发、编译和运行我的 Java 项目。今天,我正在尝试使用java.io.Console该类来管理输出,更重要的是,管理用户输入。

The problem is that System.console()returns nullwhen an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.

问题是当应用程序“通过”Eclipse 运行时System.console()返回null。Eclipse 在后台进程上运行程序,而不是在我们熟悉的控制台窗口的顶级进程上运行。

Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.

有没有办法强制 Eclipse 将程序作为顶级进程运行,或者至少创建一个 JVM 可以识别的控制台?否则,我将被迫 jar 项目并在 Eclipse 外部的命令行环境中运行。

采纳答案by McDowell

I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath.

我假设您希望能够从 Eclipse 使用逐步调试。您可以通过在 JRE 类路径上的 bin 目录中设置构建的类来在外部运行这些类。

java -cp workspace\p1\bin;workspace\p2\bin foo.Main

You can debug using the remote debugger and taking advantage of the class files built in your project.

您可以使用远程调试器并利用项目中内置的类文件进行调试。

In this example, the Eclipse project structure looks like this:

在此示例中,Eclipse 项目结构如下所示:

workspace\project\
                 \.classpath
                 \.project
                 \debug.bat
                 \bin\Main.class
                 \src\Main.java

1. Start the JVM Console in Debug Mode

1.在调试模式下启动JVM控制台

debug.batis a Windows batch file that should be run externally from a cmd.execonsole.

debug.bat是一个 Windows 批处理文件,应该从cmd.exe控制台在外部运行。

@ECHO OFF
SET A_PORT=8787
SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y
java.exe %A_DBG% -cp .\bin Main

In the arguments, the debug port has been set to 8787. The suspend=yargument tells the JVM to wait until the debugger attaches.

在参数中,调试端口已设置为8787。在暂停= Y参数告诉JVM等到调试程序连接。

2. Create a Debug Launch Configuration

2. 创建调试启动配置

In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new Remote Java Applicationconfiguration with the following settings:

在 Eclipse 中,打开调试对话框(运行 > 打开调试对话框...)并使用以下设置创建一个新的远程 Java 应用程序配置:

  • Project:your project name
  • Connection Type:Standard (Socket Attach)
  • Host:localhost
  • Port:8787
  • 项目:您的项目名称
  • 连接类型:标准(插座连接)
  • 主机:本地主机
  • 端口:8787

3. Debugging

3.调试

So, all you have to do any time you want to debug the app is:

因此,任何时候您想调试应用程序时,您所要做的就是:

  • set a break point
  • launch the batch file in a console
  • launch the debug configuration
  • 设置断点
  • 在控制台中启动批处理文件
  • 启动调试配置


You can track this issue in bug 122429. You can work round this issue in your application by using an abstraction layer as described here.

您可以在错误 122429 中跟踪此问题。您可以使用此处所述的抽象层在您的应用程序中解决此问题。

回答by perimosocordiae

As far as I can tell, there is no way to get a Console object from Eclipse. I'd just make sure that console != null, then JAR it up and run it from the command line.

据我所知,无法从 Eclipse 获取 Console 对象。我只是确保控制台 != null,然后 JAR 并从命令行运行它。

回答by Heath Borders

The reason this occurs is because eclipse runs your app as a background process and not as a top-level process with a system console.

发生这种情况的原因是 eclipse 将您的应用程序作为后台进程运行,而不是作为具有系统控制台的顶级进程运行。

回答by John Gardner

Found something about this at http://www.stupidjavatricks.com/?p=43.

http://www.stupidjavatricks.com/?p=43 上找到了一些关于此的信息

And sadly, since console is final, you can't extend it to create a a wrapper around system.in and system.out that does it either. Even inside the eclipse console you still have access to those. Thats probably why eclipse hasn't plugged this into their console yet...

可悲的是,由于控制台是最终的,您不能扩展它来创建一个围绕 system.in 和 system.out 的包装器。即使在 eclipse 控制台中,您仍然可以访问这些内容。这可能就是为什么 eclipse 还没有将它插入他们的控制台的原因......

I understand why you wouldn't want to have any other way to get a console other than System.console, with no setter, but i don't understand why you wouldn't want someone to be able to override the class to make a mock/testing console...

我理解为什么你不想有任何其他方式来获得 System.console 以外的控制台,没有 setter,但我不明白你为什么不希望有人能够覆盖类来制作一个模拟/测试控制台...

回答by Ross

There seems to be no way to get a java.io.Console object when running an application through Eclipse. A command-line console window is not opened with the application, as it is run as a background process (background to Eclipse?). Currently, there is no Eclipse plugin to handle this issue, mainly due to the fact that java.io.Console is a final class.

通过 Eclipse 运行应用程序时,似乎没有办法获得 java.io.Console 对象。命令行控制台窗口不会随应用程序一起打开,因为它作为后台进程(Eclipse 的后台?)运行。目前,没有 Eclipse 插件来处理这个问题,主要是因为 java.io.Console 是一个 final 类。

All you can really do is test the returned Console object for null and proceed from there.

您真正能做的就是测试返回的 Console 对象是否为 null 并从那里继续。

回答by Laplie Anderson

The workaround that I use is to just use System.in/System.out instead of Console when using Eclipse. For example, instead of:

我使用的解决方法是在使用 Eclipse 时只使用 System.in/System.out 而不是 Console。例如,而不是:

String line = System.console().readLine();

You can use:

您可以使用:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();

回答by Dave Richardson

This linkoffers alternatives to using System.console(). One is to use a BufferedReader wrapped around System.in, the second is to use a Scanner wrapped around System.in.

链接提供了使用 System.console() 的替代方法。一种是使用环绕 System.in 的 BufferedReader,第二种是使用环绕 System.in 的 Scanner。

Neither are as concise as console, but both work in eclipse without having to resort to debug silliness!

两者都不像控制台那样简洁,但都可以在 eclipse 中工作而不必求助于调试愚蠢!

回答by binarycube

Another option is to create a method to wrap up both options, and "fail over" to the System.in method when Console isn't available. The below example is a fairly basic one - you can follow the same process to wrap up the other methods in Console (readPassword, format) as required. That way you can run it happily in Eclipse & when its deployed you get the Console features (e.g. password hiding) kicking in.

另一种选择是创建一个方法来包装这两个选项,并在控制台不可用时“故障转移”到 System.in 方法。下面的示例是一个相当基本的示例 - 您可以按照相同的过程根据需要在 Console 中封装其他方法(readPassword、format)。这样你就可以在 Eclipse 中愉快地运行它,当它部署时,你会得到控制台功能(例如密码隐藏)。

    private static String readLine(String prompt) {
        String line = null;
        Console c = System.console();
        if (c != null) {
             line = c.readLine(prompt);
        } else {
            System.out.print(prompt);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            try {
                 line = bufferedReader.readLine();
            } catch (IOException e) { 
                //Ignore    
            }
        }
        return line;
    }

回答by yztaoj

You can implement a class yourself. Following is an example:

你可以自己实现一个类。下面是一个例子:

public class Console {
    BufferedReader br;
    PrintStream ps;

    public Console(){
        br = new BufferedReader(new InputStreamReader(System.in));
        ps = System.out;
    }

    public String readLine(String out){
        ps.format(out);
        try{
            return br.readLine();
        }catch(IOException e)
        {
            return null;
        }
    }
    public PrintStream format(String format, Object...objects){
        return ps.format(format, objects);
    }
}

回答by Paulo Merson

Let's say your Eclipse workspace is C:\MyWorkspace, you created your java application inside a maven project MyProject, and your Java main class is com.mydomain.mypackage.MyClass.

假设您的 Eclipse 工作区是 C:\MyWorkspace,您在 Maven 项目 MyProject 中创建了 Java 应用程序,并且您的 Java 主类是 com.mydomain.mypackage.MyClass。

In this case, you can run your main class that uses System.console()on the command line:

在这种情况下,您可以运行System.console()在命令行上使用的主类:

java -cp C:\MyWorkspace\MyProject\target\classes com.mydomain.mypackage.MyClass

NB1: if it's not in a maven project, check the output folder in project properties | Java Build Path | Source. It might not be "target/classes"

NB1:如果它不在maven项目中,请检查项目属性中的输出文件夹| Java 构建路径 | 来源。它可能不是“目标/类”

NB2: if it is a maven project, but your class is in src/test/java, you'll likely have to use "target\test-classes" instead of "target\classes"

NB2:如果它是一个 maven 项目,但你的类在 src/test/java 中,你可能必须使用“target\test-classes”而不是“target\classes”