2016-02-05 74 views
0

我有一個程序,我在工作中爲Java編寫了一個XML文件,它允許用戶以表格形式查看XML,進行更改,然後將表格保存爲新文件XML。使用進程生成器在Internet Explorer中打開文件Java

除了一個小細節外,一切都完成了。一旦用戶保存了表格,數據當然會被解析爲一個新的XML。然後我想要一個對話框出現,告訴用戶保存位置並詢問他們是否想打開文件。

如果用戶點擊是,那麼我想要在Internet Explorer中打開XML。我在另一個程序中成功實現了一個類似ProcessBuilder的方法,但是在那種情況下,需要使用記事本打開的文件才能完美運行。

現在我遇到的問題是,雖然InternetExplorer將打開文件不會打開,瀏覽器將只停留在主頁上。如果有人能幫助我,我會在下面發佈我的代碼,我將不勝感激!

location = "//CamT54Revised"+date+".xml"; 
      location = fHandling.saveFile.getSelectedFile()+location; 

      TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
      Transformer transformer = transformerFactory.newTransformer(); 
      DOMSource source = new DOMSource(doc); 
      StreamResult result = new StreamResult(new File(location)); 
      transformer.transform(source, result); 

      int dialogResult = JOptionPane.showConfirmDialog(null, "Output file saved as "+location+". Would you like to view the file?","Display Output",JOptionPane.YES_NO_OPTION); 
      if(dialogResult==JOptionPane.YES_OPTION){ 

       ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Internet Explorer\\iexplore.exe", location); 
       try{ 
        pb.start(); 
       }catch(IOException e){ 
        e.printStackTrace(); 
       } 

      } 
+0

Windows不使用正斜槓(''//),所以'location'值不被IE理解。爲什麼它甚至從「//」開始呢? – Andreas

回答

0

假設的Internet Explorer是默認的瀏覽器,你可以使用桌面API對這一問題。

public class DesktopTest { 

    public static void main(String args[]) { 

     if (!Desktop.isDesktopSupported()) { 
      System.err.println("Desktop not supported!"); 
      System.exit(-1); 
     } 

     Desktop desktop = Desktop.getDesktop(); 
     File file = new File(args[0]); 

     if (desktop.isSupported(Desktop.Action.OPEN)) { 
      try { 
       desktop.open(file); 
      } 
      catch (IOException ioe) { 
       System.err.println("Unable to open: " + file.getName()); 
      } 
     } 
    } 
} 

但是,如果您想實際強制使用Internet Explorer,那麼您可能不得不求助於流程構建器。

+0

我確實需要強制Internet Explorer。如果我使用這種方法,它將用記事本打開,這是無用的,因爲它不會是一種易於閱讀的格式。建議? – jesric1029

2

相反的ProcessBuilder,我會建議你使用Desktop.open(File)啓動關聯的應用程序打開該文件。喜歡的東西,

File f = new File(location); 
Desktop.open(f); 
+0

我相信OP的真正問題是'location'值開頭的'//',但我同意這是OP「打開文件」的更好方式,就像OP所說的那樣。 +1通過'File'對象處理'location'值會將'//'轉換爲'\\',但'\\ filename'在Windows中不是一個有效的路徑,所以也可能不起作用。 – Andreas

+1

Andreas - 如果你說的是真的,那麼當我使用「C:\\ Program Files \\ Internet Explorer \\ iexplore.exe」時,Internet Explorer仍然會打開? (只是不與我的文件)。 與您的建議埃利奧特的問題是,我需要強制Internet Explorer打開文件,否則該文件將只用記事本打開,它不會以用戶可以理解的格式。 – jesric1029

0
Runtime runtime = Runtime.getRuntime(); 
Process process = runtime.exec("C:\\path\\to\\notepad.exe C:\\path\\to\\file.txt"); 

第一路徑是要在其中打開第二道程序 - 特定文件

相關問題