Java:如何检查另一个 class 文件是否为 运行?

Java: How do i check if another class file is running?

嗯,我正在做一个项目来测试我的 java 编程知识。

我的项目是一个游戏,我正在为其制作某种启动器,当项目完全启动时它会关闭。我在网上搜索以了解如何检查 java 程序是否为 运行。我找到了一种方法来查看程序是否为 运行(here is the link to it 或参见下面的代码)。我测试了它但它没有用所以我搜索了答案以检查 process/program 是否是 运行 在 "bigger" 程序下(例如:多个 windows 在 firefox 中) .我没有找到所以我希望你知道答案。

这里是检查程序是否是我发现的 运行 (And here is the link again) 的方法:

String line;
String pidInfo ="";

Process p =Runtime.getRuntime().exec(System.getenv("windir") +"\system32\"+"tasklist.exe");

BufferedReader input =  new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = input.readLine()) != null) {
    pidInfo+=line; 
}

input.close();

if(pidInfo.contains("file.class"))
{
    // do what you want
}

您可以检查文件的内容,而不是检查游戏进程是否为 运行(pid 不太可能,因为这是一个数字) 13=]

File f = new File("path_to_file.txt");
BufferedReader br;
String text = "";
try {
     br= new BufferedReader(new FileReader(f));
     String line;
     while((line = br.readLine())!=null){
         text+=line;
     }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
if(text.equals("started")){
    // we have to make sure it can work next time so we clear the file's contents
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("");
        bw.flush();
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //close launcher
}

然后唯一剩下要做的就是让游戏在开始后向该文件写入文本 "started"