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;
else
command = 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:
[url]http://hi.baidu.com/%D5%D4%B7%F6%B7%E7/blog/item/f10ef7ece09e37c42f2e21eb.html[/url]
[url]http://www.iteye.com/problems/9241[/url]
[url]http://hi.baidu.com/mikeymouse01/blog/item/7eae62f2fd6b6940342accc9.html[/url]
[url]http://flyeagle.iteye.com/blog/406487[/url]
[url]http://dingbuoyi.iteye.com/blog/836721[/url]
Java 文件路径中特殊符号问题
[url]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[/url]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值