从Java打开文档的更好方法?
时间:2020-03-05 18:50:56 来源:igfitidea点击:
我一直使用以下代码在Windows机器上使用Java打开Office文档,PDF等,并且运行正常,但出于某种原因,文件名将其嵌入多个连续的空格(例如" File [SPACE] [ SPACE] Test.doc"。
我该如何进行这项工作?我不反对编写完整的代码...但是我不希望将其替换为调用JNI的第三方库。
public static void openDocument(String path) throws IOException { // Make forward slashes backslashes (for windows) // Double quote any path segments with spaces in them path = path.replace("/", "\").replaceAll( "\\([^\\\\\"]* [^\\\\\"]*)", "\\\\"\""); String command = "C:\Windows\System32\cmd.exe /c start " + path + ""; Runtime.getRuntime().exec(command); }
编辑:当我用错误的文件运行它时,Windows会抱怨找不到文件。但是...当我直接从命令行运行命令行时,它运行得很好。
解决方案
回答
如果使用的是Java 6,则可以使用java.awt.Desktop的open方法使用当前平台的默认应用程序启动文件。
回答
不知道这是否对我们有很大帮助...我使用Java 1.5+的ProcessBuilder在Java程序中启动外部Shell脚本。基本上,我会执行以下操作:(尽管这可能并不适用,因为我们不想捕获命令输出;我们实际上想启动文档,但是,这可能会激发我们可以使用的东西)
List<String> command = new ArrayList<String>(); command.add(someExecutable); command.add(someArguemnt0); command.add(someArgument1); command.add(someArgument2); ProcessBuilder builder = new ProcessBuilder(command); try { final Process process = builder.start(); ... } catch (IOException ioe) {}
回答
问题可能出在我们使用的"开始"命令,而不是文件名解析。例如,这似乎在我的WinXP机器上运行良好(使用JDK 1.5)
import java.io.IOException; import java.io.File; public class test { public static void openDocument(String path) throws IOException { path = "\"" + path + "\""; File f = new File( path ); String command = "C:\Windows\System32\cmd.exe /c " + f.getPath() + ""; Runtime.getRuntime().exec(command); } public static void main( String[] argv ) { test thisApp = new test(); try { thisApp.openDocument( "c:\so\My Doc.doc"); } catch( IOException e ) { e.printStackTrace(); } } }