使用java的简单控制台应用程序

使用java的简单控制台应用程序,java,Java,我正在用java开发一个简单的控制台应用程序。代码如下所示 ` try { File file = new File("writer.txt"); writer = new BufferedWriter(new FileWriter(file)); Process myProcess = Runtime.getRuntime().exec("jps -l"); BufferedReader std

我正在用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();
           }
`    
代码将在我的windows中显示当前正在运行的jar。输出格式显示为
2356 Timeout.jar
我只想显示
Timeout.jar
如何删除该整数值。提前感谢。

您可以:

  • 将正则表达式应用于行,然后再将其写出。(想想行的开头,然后是整数,最后是第一个空格)
  • 使用ls(或dir)作为exec进程,而不是jps
  • 只需直接抓取目录列表,而不是通过外部流程,如下所示:
File dir=新文件(“目录名”)

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.
  • 将结果标记化是一种方法

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

  • 假设您在
    行中有“2356 Timeout.jar”,这将只返回jar名称:

    line.substring(line.indexOf(" ") + 1);
    
    我认为一定有一种更简单的方法来获得运行的jar。我快速搜索了一下,您可能想看看这些问题:


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

    而不是

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

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