我遇到同樣的問題,因爲你。我發現了一個相當不錯的解決方案,我建議在確保該過程正式啓動之前稍微休息一下。
Process p = Runtime.getRuntime().exec("cmd /c tasklist");
StringWriter writer = new StringWriter();
IOUtils.copy(p.getInputStream(), writer);
String theString = writer.toString();
//System.out.println(theString);
id = findLastString("javaw.exe .{1,} Console 1", theString);
System.out.println(id);
其中findLastString被定義爲
public static String findLastString(String pattern, String in) {
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(in);
String it= "";
while(matcher.find()) {
it = matcher.group();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int firstIndex=pattern.indexOf(".{1,}");
int lastIndex=it.substring(firstIndex).indexOf(pattern.substring(pattern.indexOf(".{1,}")+5))+firstIndex;
String dotOn = it.substring(pattern.indexOf(".{1,}"));
it=it.substring(firstIndex, lastIndex);
return it;
}
基本上這將讓正在運行的進程的列表,並找到最近跑了一個用,在這種情況下,名稱的javaw.exe(我的程序開始一個單獨的java進程)。您可以將javaw.exe替換爲進程的名稱,您可以使用任務管理器找到它。您也需要獲得Apache常見的IO jar。
我認爲這會給出JVM進程的PID ......而不是Java產生的進程,我相信這是問題的要求。 – splashout
我認爲你需要仔細閱讀。它產生了一個進程,只有工作是將它自己的PID回顯到它本身被連接到與JVM關聯的stdin文件描述符的stdout。 – nsfyn55
向量是舊式的,並且是同步的 - 沒有真正需要使用該類型的集合 - 請嘗試使用ArrayList。只是說。 – user924272