我正在使用Java 1.5,并且想启动相关的应用程序来打开文件。我知道Java 1.6引入了Desktop API,但是我需要 Java 1.5 的解决方案。
到目前为止,我找到了在Windows中执行此操作的方法:
Runtime.getRuntime().exec(new String[]{ "rundll32", "url.dll,FileProtocolHandler", fileName });
有跨平台的方法吗?或者至少是针对 Linux 的类似解决方案?
另外,我建议使用多态性进行以下实现:
这样,您可以通过减少类之间的耦合来更轻松地添加新平台。
客户端代码:
Desktop desktop = Desktop.getDesktop(); desktop.open( aFile ); desktop.imaginaryAction( aFile );
桌面展示:
package your.pack.name; import java.io.File; public class Desktop{ // hide the constructor. Desktop(){} // Created the appropriate instance public static Desktop getDesktop(){ String os = System.getProperty("os.name").toLowerCase(); Desktop desktop = new Desktop(); // This uf/elseif/else code is used only once: here if ( os.indexOf("windows") != -1 || os.indexOf("nt") != -1){ desktop = new WindowsDesktop(); } else if ( os.equals("windows 95") || os.equals("windows 98") ){ desktop = new Windows9xDesktop(); } else if ( os.indexOf("mac") != -1 ) { desktop = new OSXDesktop(); } else if ( os.indexOf("linux") != -1 && isGnome() ) { desktop = new GnomeDesktop(); } else if ( os.indexOf("linux") != -1 && isKde() ) { desktop = new KdeDesktop(); } else { throw new UnsupportedOperationException(String.format("The platform %s is not supported ",os) ); } return desktop; } // default implementation :( public void open( File file ){ throw new UnsupportedOperationException(); } // default implementation :( public void imaginaryAction( File file ){ throw new UnsupportedOperationException(); } } // One subclass per platform below: // Each one knows how to handle its own platform class GnomeDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: execute gnome-open <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec:gnome-something-else <file> } } class KdeDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: kfmclient exec <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec: kfm-imaginary.sh <file> } } class OSXDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: open <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec: wow!! <file> } } class WindowsDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: cmd /c start <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec: ipconfig /relese /c/d/e } } class Windows9xDesktop extends Desktop{ public void open( File file ){ //Runtime.getRuntime().exec: command.com /C start <file> } public void imaginaryAction( File file){ //Runtime.getRuntime().exec: command.com /C otherCommandHere <file> } }
这只是一个例子,在现实生活中不值得仅通过参数化值(命令字符串%s)来创建一个新类,但是让我们想象一下每种方法都以平台特定的方式执行另一个步骤。
采取这种方法,可能会删除不必要的if / elseif / else结构,这些结构会随着时间的推移而引入错误(如果代码中有6个错误,并且需要更改,您可能会忘记更新其中之一,或者通过复制/粘贴,您可能会忘记更改要执行的命令)