使用java的简单控制台应用

时间:2010-07-01 04:38:16

标签: java

我使用java开发一个简单的控制台应用程序。代码如下:

`   try {
            File file = new File("writer.txt");
            writer = new BufferedWriter(new FileWriter(file));
            Process myProcess = Runtime.getRuntime().exec("jps -l");
            BufferedReader stdout = new BufferedReader(new InputStreamReader(
                    myProcess.getInputStream()));
            String line = stdout.readLine();
            while (line != null) {
                if (line.contains(".jar")) {
                    writer.write(line);
                    System.out.println(line);
                }
                line = stdout.readLine();
            }
            writer.close();
           }
`    

代码将在我的窗口中显示当前运行的jar。显示输出格式2356 Timeout.jar我只想显示它Timeout.jar如何删除整数值。提前谢谢。

4 个答案:

答案 0 :(得分:1)

假设line中有“2356 Timeout.jar”,这将只返回jar名称:

line.substring(line.indexOf(" ") + 1);

我认为必须有一种更简单的方法来获得正在运行的jar。我做了一个快速搜索,你可能想看看这些问题:

答案 1 :(得分:0)

你可以:

  • 在写出之前,将正则表达式应用于。 (想想行首,然后是整数,以第一个空格结束)
  • 使用ls(或dir)作为exec进程而不是jps
  • 直接抓取目录列表,而不是通过外部流程获取,如下所示:

File dir = new File("directoryName");

String[] children = dir.list();

由于jps手册页中的以下注释,如果这不是一个快速的一次性应用程序或学习练习,那么通过JPS执行操作可能不是一个好主意:

NOTE- You are advised not to write scripts to parse  jps  output  since
       the  format  may  change  in  future  releases.  If you choose to write
       scripts that parse  jps  output,  expect  to  modify  them  for  future
       releases of this tool.

答案 2 :(得分:0)

  1. 对结果进行标记是一种方式。

  2. 如果您使用的是unix,请使用awk获取第二个字段。

答案 3 :(得分:0)

如果您使用的是基于Linux的操作系统,

而不是

Process myProcess = Runtime.getRuntime().exec("jps -l");

尝试这个

Process myProcess = Runtime.getRuntime().exec("jps -l | cut -d \" \" -f2");
相关问题