2015-07-13 92 views
1

我有這樣一段代碼:Desktop.getDesktop.open()在Java中失敗

public void openSelectedFiles(MouseEvent mouseEvent){ 
    ListView<String> listView = (ListView<String>) ((Node) mouseEvent.getSource()) 
     .getScene().lookup("#listOfReferenceFiles"); 

    String selectedFileString = listView.getSelectionModel().getSelectedItem(); 
    System.out.println(Desktop.isDesktopSupported()); 
    File fileToOpen = new File(selectedFileString); 
    System.out.println(fileToOpen.exists()); 

    try { 
     Desktop.getDesktop().open(fileToOpen); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

我使用Java 8,它似乎是工作,直到這條線:

Desktop.getDesktop().open(fileToOpen);

它不會拋出異常,它只會凍結我的應用程序。這是一個錯誤?

+1

文件'fileToOpen'存在? –

+1

如果System.out.println(Desktop.isDesktopSupported())打印爲true,我很想回答yes。 – wero

+0

是的,他們打印真實的,和文件存在/ –

回答

0

如果桌面允許你必須首先檢查,如果文件存在,以避免這種問題:

//first check if Desktop is supported by Platform or not 
if(!Desktop.isDesktopSupported()){ 
    System.out.println("Desktop is not supported"); 
    return; 
} 

Desktop desktop = Desktop.getDesktop(); 

// after check if file exists and open it 
if(file.exists()) desktop.open(file); 
+0

試過了。複製完全相同的代碼。沒有。我也一樣 –