java操作文件和调用windows命令的一个例子

1、调用windows命令

commandString = “cmd /c dir”;

Runtime.getRuntime().exec(commandString);

如果命令后的参数有空格的话,务必要用引号把参数括起来。

不幸的是,如果参数有两个以上的空格,即使用了引号也会出错,真正执行命令的参数只会保留一个空格。变通的方法就是下面示例的创建批处理文件。

2、创建批处理文件

public static void createBatFile(String fileName) {

File file;

FileOutputStream fos = null;

PrintWriter pw = null;

try {

file = new File(“d:\caclsbat.bat”);

if (!file.exists()) {

file.createNewFile();

}

fos = new FileOutputStream(file);

pw = new PrintWriter(fos);

String command = “cacls “” + fileName + “”";

pw.write(command.toCharArray());

pw.flush();

fos.close();

} catch (Exception e) {

System.out.println(e);

}

}

3. 通过调用cacls命令获取文件的授权信息

public static String getPrivilege(String folderName) {

try {

String commandString;

if (folderName.indexOf(”
“) > -1) {

createBatFile(folderName);

commandString = “d:\caclsbat.bat”;

} else {

commandString = “cacls “” + folderName + “”";

}

commandString = “cmd /c ” + commandString;

Process process = Runtime.getRuntime().exec(commandString);

InputStream is = process.getInputStream();

InputStreamReader inputStreamReader = new InputStreamReader(is);

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String ss = new String();

String s;

while ((s = bufferedReader.readLine()) != null) {

ss += s;

}

ss = ss.toLowerCase();

return ss;

} catch (Exception e) {

System.out.println(e);

}

return null;

}

4. 文件遍历,用递归实现。

public static void dir(File file, boolean debug) throws IOException {

if (file.isDirectory()) {

File[] files = file.listFiles();

if (files != null) {

for (int i = 0; i < files.length; i++) {

if (files[i].isDirectory()) {

String folderName = files[i].getPath() + “\”;

String ss = getPrivilege(folderName);

if (debug) {

System.out.println(ss);

}

if (!(ss.indexOf(“domain\administrator”) > -1 || ss.indexOf(“domain\fileserveradmin”) > -1)) {

System.out.println(folderName);

}

dir(files[i], debug);

}

}

}

}

}

Comments are closed.