2014-06-16 132 views
0

这是this的后续问题。未找到控制台。如何让我的JVM的控制台?

我昨天问过这个问题,虽然它尚未解决,我试图对代码做一些愚蠢的变化,只是让它一次编译(由System.out.print语句替换console.format()报表,并添加null作为第二个参数到readLine()方法)。

幸运的是,代码并运行,但它打印No console.(显然是因为JVM没有一个控制台设备。Reference

所以,我怎么能得到控制台设备,应该是代表由控制台类的对象?


为了方便起见,我加入的代码后,我做给它的上述愚蠢的变化,使其运行: -

import java.io.Console; 
import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

/* 
* Enter your regex: foo 
* Enter input string to search: foo 
* I found the text foo starting at index 0 and ending at index 3. 
* */ 

public class RegexTestHarness { 

    public static void main(String[] args){ 
     Console console = System.console(); 
     if (console == null) { 
      System.err.println("No console."); 
      System.exit(1); 
     } 
     while (true) { 

      Pattern pattern = 
      Pattern.compile(console.readLine("%nEnter your regex: ", null)); 

      Matcher matcher = 
      pattern.matcher(console.readLine("Enter input string to search: ", null)); 

      boolean found = false; 
      while (matcher.find()) { 
       /*console.format("I found the text" + 
        " \"%s\" starting at " + 
        "index %d and ending at index %d.%n", 
        matcher.group(), 
        matcher.start(), 
        matcher.end());*/ 

       System.out.println("I found the text " + matcher.group() + " starting at index " + matcher.start() + " and ending at index " + matcher.end() + "."); 

       found = true; 
      } 
      if(!found){ 
       //console.format("No match found.%n", null); 
       System.out.println("No match found."); 
      } 
     } 
    } 
} 
+0

你如何运行此代码?我有一种感觉,你正在使用Eclipse,NetBeans或InteliiJ等IDE。 – Pshemo

+0

是的,我使用Eclipse。 – Solace

+1

在这种情况下[this](http://stackoverflow.com/a/23981357/1393766)可能会让你感兴趣。 – Pshemo

回答

0

您的应用程序只会有一个控制台设备打开如果它是从终端启动的,并且没有标准输入或标准输出重定向。 基本上函数isatty()将不得不返回true。如果Windows应用程序是从资源管理器启动的,则它们通常没有控制台。您应该从命令提示符(cmd.exe)启动它们。