java - 在控制台应用程序上使用 .readline() 时出现间歇性结果
问题描述
我有一个试图从中读取的外部控制台应用程序。我的代码启动 .exe 进程。我使用的是缓冲阅读器、.getinputstream,然后是 .readLine。然后我将 Line 打印到控制台。我这样做有一些意想不到的结果。
- 启动进程后,我在任务管理器进程中看不到它。我使用 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 ;
}
}
解决方案
解决方案是删除额外的“.readline”。代码在第二个 .readline 上写了一个长度为 0 的字符串,这让我相信我没有得到数据。该解决方案已在此论坛中提供给我。
推荐阅读
- r - 仅在 rstudio 服务器上的 foreach / dofuture 抛出错误
- php - 如何通过echo在PHP中显示html类HTML?
- android - 每次打开 CustomDialogFragment 时都会初始化 ArrayList
- python - 批量转换作业导致数据文件 >100MB 的“InternalServerError”
- c++ - 使用 SFINAE 检查函数 std::to_string 是否存在
- firebase - Google Cloud Platform - 仅允许 App Engine 在内部访问,或从 Firebase 托管的应用程序访问
- angular - 使用 Angular 7 在 IndexedDB 中添加价值
- javascript - 使用 Angular 的 Soap 服务上传附件
- c# - 如何在 C# 中读取资源文件
- android - 为什么后期 init var 不能与 Nullable 一起使用?