---
title: "java 执行windows程序"
author: "suifeng"
date: "2009-05-14T15:51:34Z"
tags: []
categories: ["非技术"]
slug: "java-windows"
draft: false
lastmod: "2009-05-14T16:00:38Z"
id: 386902
url: "https://pipe-line.iteye.com/blog/386902"
---

java执行windows程序很简单, 一句话搞定

 

```
Runtime.getRuntime().exec("cmd /c echo hello world!");
```

```
Runtime.getRuntime().exec("notepad.exe");
```

 

 

但是要在要做安全管理下执行, 那就不容易了---折腾了两天, 终于解决了.

 

说来也简单, 就是修改 java.policy文件 ($(dir)\\jre\\lib\\security\\java.policy) 里面 加入一句 

 

```
   permission java.io.FilePermission "exe_path", "execute";
```

 

 

但是 exe\_path 却折腾人, 折腾出来的经验是:

1, exe\_path必须使用绝对路径

2, windows下的路径分隔符 要使用 \\\\ 双杠(最初使用单杠 总是报异常, 看来jvm对待java.policy像java代码一样, 是转义的, 使用/分割也行).

 

对于上面的exe\_path处, 也可以使用 &lt;&lt;ALL FILES&gt;&gt;，但是它授权给所有文件，java文档里面指出一定要慎重．

 

 

参考:

[企业内部网中使用Policy文件来设置Java的安全策略](http://www.infosecurity.org.cn/article/websec/java/23218.html)

 

## [FilePermission](http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/io/FilePermission.html)

[java安全管理器](http://lingqi1818.iteye.com/blog/350581)

 

 

附 : windows 中有个 tasklist程序, 可以查看每个进程使用的cpu时间, 据初步验证可以根据tasklist /v的输出,计算cpu的使用率; 对于服务器cpu使用率监控程序, 可以据此实现. 尤其要注意cpu的个数.

大致有如下 数学关系

 

cpu个数  *  时间 ==  各进程总cpu时间

 

对于某个进程P, 在时间点t1的cpu时间为 cpu1, 

在时间点 t2 的cpu时间为 cpu2

那么在t2到t1之间cpu的占用率为

 

p的cpu的使用率 = (cpu2 - cpu1) / ((t2-t1) * cpu个数)

 

把p设置成 空闲进程, 那么 1- p的cpu的使用率 就是 系统的cpu使用率.

 

执行 echo %number\_of\_processors% 可以获取cpu个数或核数