首页 > 解决方案 > 在控制台应用程序上使用 .readline() 时出现间歇性结果

问题描述

我有一个试图从中读取的外部控制台应用程序。我的代码启动 .exe 进程。我使用的是缓冲阅读器、.getinputstream,然后是 .readLine。然后我将 Line 打印到控制台。我这样做有一些意想不到的结果。

  1. 启动进程后,我在任务管理器进程中看不到它。我使用 isAlive() 来验证进程是否已实际启动,并且它返回 true。如果我在单独的 java 文件中运行该进程,该进程将正确启动。我可以在任务管理器进程中看到它。

2)运行代码时,我得到间歇性的结果。大多数时候 .println(Line) 不打印任何东西(在日食中)。我已经看到 println 在这段代码上工作了几次,但是它并没有一直在工作。

我只用 java 写了大约两个星期,所以我对这些函数的大部分工作原理的理解是补救性的。我觉得这要么是 .exe 和我的代码之间的时间问题,要么是我出于错误的目的使用了某些东西,并且使某些事情变得比必须的更难。任何帮助将不胜感激。

Windows 10、Eclipse IDE

public class P3Data {

public static void main(String[] args) throws IOException {

try {
        //OutputStream r = P3d.getOutputStream();
        //PrintStream ps = new PrintStream(r);
    
        //System.out.println(ps.toString());
                
                if (Ignition().isAlive() ) {
                    String alive = new String("Tagged is on");
                    System.out.println("the program "+alive);
                }
        
         String line;
        BufferedReader input = new BufferedReader(new InputStreamReader(Ignition().getInputStream()));
        {
            while ((line = input.readLine()) != null) {
              line = input.readLine();
                //TimeUnit.SECONDS.sleep(1);
                System.out.println(line);
            //System.out.println("P3d running");
            }           
            
             input.close();
        }
                        
    } catch (Exception e) {
        e.printStackTrace();
        
        
        
    }
            
  System.out.println("Program ended");
 }

public static Process Ignition() throws IOException{
            
             String appname = new String("Consoledata.exe");
             String Fname = new  String("C:\\Users\\...\"+ appname);
            
    String command[] = {Fname};  
    
    ProcessBuilder Prep =new ProcessBuilder(command);
    
    Process P3d = Prep.start();
   return P3d ;
    
}

}

标签: java

解决方案


解决方案是删除额外的“.readline”。代码在第二个 .readline 上写了一个长度为 0 的字符串,这让我相信我没有得到数据。该解决方案已在此论坛中提供给我。

https://www.javaprogrammingforums.com/file-io-other-io-streams/43884-using-external-exe-input-stream.html#post172381


推荐阅读