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;}