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();开发者_Go百科
}
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.
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:
- How to get the path of a running JAR file?
- http://arstechnica.com/civis/viewtopic.php?f=20&t=261563
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.
Tokenizing the result is one way.
if you are in unix, use awk to get the second field.
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");
精彩评论