读书人

java RunTime.getRuntime.exec()运用外

发布时间: 2012-09-22 21:54:54 作者: rapoo

java RunTime.getRuntime.exec()使用外部命令,特殊字符
这样一段java代码:

        // 最初的/*private static final String FILE_COMMAND_WIN = "file.exe %s";private static final String FILE_COMMAND_LINUX = "file %s";*/        // 最终的private static final String FILE_COMMAND_WIN = "file.exe";private static final String FILE_COMMAND_LINUX = "file"public static String getFileCommandResult(String file) throws IOException {Process process = null;InputStream in = null;InputStreamReader reader = null;BufferedReader bufferedReader = null;String result = null;try {String command;if (Util.isWindows())command = FILE_COMMAND_WIN;elsecommand = FILE_COMMAND_LINUX;                                //(0)最初的设计,不能解决file中特殊字符的问题,path和文件名字有空格或特殊字符,程序会在这里hang住        //process = Runtime.getRuntime().exec(String.format(command, file));                                //(1)这样程序不会hang住,但是shell命令提示找不到这个文件/*File oldFile = new File(file);String temp = oldFile.toURI().getRawPath();System.out.println(temp);*/        //(2)这样程序程序也会hang住/*String temp = file.replace(" ", "\" \"");System.out.println(temp);process = Runtime.getRuntime().exec(String.format(command, temp));*/                //最终的。exec的重载输入可以是个字符数组        //将命令和参数分开,避免exec自己以空格去划分。String[] commands = new String[2];commands[0] = command;commands[1] = file;//System.out.println(commands.toString());process = Runtime.getRuntime().exec(commands);in = process.getInputStream();reader = new InputStreamReader(in);bufferedReader = new BufferedReader(reader);result = bufferedReader.readLine();} finally {if (bufferedReader != null)bufferedReader.close();if (process != null)process.destroy();}return result;}


reference:
http://hi.baidu.com/%D5%D4%B7%F6%B7%E7/blog/item/f10ef7ece09e37c42f2e21eb.html
http://www.iteye.com/problems/9241
http://hi.baidu.com/mikeymouse01/blog/item/7eae62f2fd6b6940342accc9.html
http://flyeagle.iteye.com/blog/406487
http://dingbuoyi.iteye.com/blog/836721
Java 文件路径中特殊符号问题
http://wisdombase.net/wiki/index.php?title=Java_%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84%E4%B8%AD%E7%89%B9%E6%AE%8A%E7%AC%A6%E5%8F%B7%E9%97%AE%E9%A2%98

读书人网 >编程

热点推荐