2007年7月30日星期一

如何在Java中直接打开文件

我们经常会遇到这种情况:将Applet的显示内容按照某种格式(PDF,Excel, Word等)直接打开。那么如和实现这个功能呢。

我们分两个步骤来完成。
1.首先是将显示内容按照对应的格式生成并保存在用户的临时文件夹。

File file = File.createTempFile(getValidFileName(fileName), "." + getOutputExtension());

如何生成文件的代码略去。

2.然后调用相应的程序来打开。
String filePath =file.getPath();
Runtime.getRuntime().exec(new String[] {"cmd.exe", "/C", filePath });


在大多数情况下工作的很好, 但是如果文件名中出现一下字符“ &<>[]{}^=;!’+,`~”, 上述代码无法打开文件,同时也没有报错, 和没有执行一样。 问题出在那里的?

原来Ccmd 命令对文件名中出现这些字符要做加引号才能正确处理。 以下是cmd的说明:

The completion code deals correctly with file names that contain spaces
or other special characters by placing quotes around the matching path.
Also, if you back up, then invoke completion from within a line, the
text to the right of the cursor at the point completion was invoked is
discarded.

The special characters that require quotes are:
space
&()[]{}^=;!'+,`~


因此我们只要加一个函数来处理就可以, 代码如下:

private String getValidFilePath(String filePath)
{
Pattern p = Pattern.compile( "\\p{Punct}" );
Matcher m = p.matcher(filePath);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "\"$0\"");
}
m.appendTail(sb);

return sb.toString();
}

修改后的代码如下:
String filePath = getValidFilePath (file.getPath());
Runtime.getRuntime().exec(new String[] {"cmd.exe", "/C", filePath });

没有评论: