java - 无法使用 Java 程序从控制台中提取字符串

标签 java linux console

我有代码段:

public static void getOS() throws IOException, InterruptedException
   {
       String[] cmd = {"cat", "/etc/*-release"};
       Process proc = rt.exec(cmd);
       VerboseMode.verboseOut(cmd,proc);

       BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
       line = is.readLine();
       OS = line.trim();
   }

在一个曾经工作的程序中,但由于某种原因停止了。如果我从终端运行 cat/etc/*-release 我会得到结果,但是从 java 我得到 null。缺少什么?

已修复。

我删除了将输出定向到控制台而不是行变量的详细模式行,并更改了 cmd 字符串的格式:

public static void getOS() throws IOException, InterruptedException
   {
       String[] cmd = {"/bin/sh","-c","cat /etc/*-release" };
       Process proc = rt.exec(cmd);

       BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
       line = is.readLine();
       OS = line.trim();
   }

一定是我改了忘记了。但是对于我自己的信息,上面显示的两个 cmd 字符串之间有什么区别,以及我是否将它作为字符串与 string[] 传递。据我了解,字符串可能并不总是有效,但字符串 [] 会。但是/bin/sh -c 部分我不确定,只是之前在其他 S.O. 在线看到过。线程。

最佳答案

在字符串中你可以提供你正在通过终端运行的脚本

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Multipleprocess {

public static void main(String[] args)throws Exception {
int process=0;
String s[]={"/bin/sh","-c","cat /etc/*-release" };
Process p=Runtime.getRuntime().exec(s);
BufferedReader proc=new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader pout=new BufferedReader(new InputStreamReader(p.getInputStream()));
// We read stderror first from String because it spits the progress information 
//into   stderr

for (String s1=proc.readLine(); s1!=null; s1=proc.readLine())
{
process++;
System.out.println("Stderr from p: "+s);
}
for (String s1=pout.readLine(); s1!=null; s1=pout.readLine())       
{
process++;
System.out.println("Stdout from p: "+s);
}

//how many process have completed check here 
System.out.println("process have completed"+process);
// if you need to check whether the command actually returned normally

int returnCode = p.waitFor();
proc.close();
pout.close();

System.out.println("Process exited with return code "+returnCode);
}
}

我已经检查了我的程序在我的 eclipse 上运行,你可以使用我的程序,我得到这样的输出:

Stderr from p: [Ljava.lang.String;@186d4c1
Stderr from p: [Ljava.lang.String;@186d4c1
Stderr from p: [Ljava.lang.String;@186d4c1
Stderr from p: [Ljava.lang.String;@186d4c1
process have completed16

进程退出,返回码为 0 你可以在这里看到进程完成 16

关于java - 无法使用 Java 程序从控制台中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18023528/

相关文章:

java - 如何从 SpringBoot 应用程序发出自定义指标并在 PCF Autoscaler 中使用它

java - Windows Server 2003(32 位)终端服务上的 Java RE 1.7.0 存在问题吗?

linux - 如何从剪贴板读取文本?

php - Symfony: fatal error :在应用程序/控制台中找不到类

eclipse - 如何将 linux 终端输出重定向到 Eclipse 控制台?

java - 当 session 被销毁时,Tomcat Session 中保存的值是否应该设置为 null?

java - 正则表达式用新行数替换注释

linux - 如何直接从lvm pv盘恢复数据

linux - top 命令在 for 循环中运行时显示额外的 10 行

console - 无法在 PyCharm 中使用 IPython 控制台