Java 取得 Process ID

摘要:Java 取得 Process ID

 

    public long getPID() {
        String processName =
                java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        return Long.parseLong(processName.split("@")[0]);
    }
 
    public void createPidFile() {
        try {
            long pid = this.getPID();
 
            String filePath = "java.pid"
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"big5");
            outputStreamWriter.write(String.valueOf(pid));
            outputStreamWriter.close();
            fileOutputStream.close();
            outputStreamWriter =null;
            fileOutputStream =null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }