如何通过Java关闭MS Office应用程序中的打开文件?

时间:2016-11-11 01:51:11

标签: java ms-office

例如,我在Windows 10上的Microsoft PowerPoint 2013中打开test.pptx。我想在不关闭Microsoft PowerPoint本身的情况下关闭它。我怎么能用Java 1.8做到这一点?

1 个答案:

答案 0 :(得分:0)

由于它的外部程序,您需要kill PC 运行功率点 task
您可以使用以下Java代码

来实现它
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ClosePowerPoint {

    private static final String TASKLIST = "tasklist";
    private static final String KILL = "taskkill /IM ";

    public static void main(String args[]) throws Exception {    
        System.out.print(isProcessRunging("POWERPNT.EXE"));

        if (isProcessRunging(processName)) {

            killProcess(processName);
        }
    }

    public static boolean isProcessRunging(String serviceName) throws Exception {

        Process p = Runtime.getRuntime().exec(TASKLIST);
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;

        while ((line = reader.readLine()) != null) {

            System.out.println(line);
            if (line.contains(serviceName)) {
                return true;
            }
        }
        return false;
    }

    public static void killProcess(String serviceName) throws Exception {

        Runtime.getRuntime().exec(KILL + serviceName);

    }   
}