lakshmi
lakshmi

Reputation: 4999

simple console Application using java

Im developing a simple console Application using java. The code is given below

`   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();
           }
`    

The code will display the currently running the jar in my windows. The output format is displayed 2356 Timeout.jar I want to display it only Timeout.jar How to remove that integer values. Thanks in advance.

Upvotes: 0

Views: 1018

Answers (4)

Sastrija
Sastrija

Reputation: 3384

If you are using a Linux based OS,

Instead of

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

try this one

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

Upvotes: 0

takteek
takteek

Reputation: 7110

Assuming you have "2356 Timeout.jar" in line, this will return just the jar name:

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

I think there must be an easier way to get the running jar though. I did a quick search and you may want to look at these questions:

Upvotes: 1

Prem Rajendran
Prem Rajendran

Reputation: 726

  1. Tokenizing the result is one way.

  2. if you are in unix, use awk to get the second field.

Upvotes: 0

G__
G__

Reputation: 7111

You could:

  • Apply a regular expression to line before writing it out. (Think start-of-line, then integers, ending at the first whitespace)
  • Use ls (or dir) as your exec process instead of jps
  • Just grab the directory listing directly instead of via the external process as per below:

File dir = new File("directoryName");

String[] children = dir.list();

Doing what you have via JPS is probably not a good idea if this isn't a quick one-off app or a learning exercise because of the following note from the jps man page:

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.

Upvotes: 0

Related Questions