2012-06-10 69 views
2

我已經做了一個按鈕,但我現在不知道如何使它打開一個特定的目錄,如%appdata%點擊按鈕時。如何製作一個按鈕,點擊後打開%appdata%目錄?

這裏是代碼 - >

//---- button4 ---- 
     button4.setText("Texture Packs"); 
     button4.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) 
      { 
       JFileChooser fileChooser=new JFileChooser("%appdata%"); 
       int status = fileChooser.showOpenDialog(this); 
       fileChooser.setMultiSelectionEnabled(false); 

       if(status == JFileChooser.APPROVE_OPTION) { 
        File file = fileChooser.getSelectedFile(); 
        // do something on the selected file. 
       } 


      } 

我想讓這樣的事情 - >

private void button4MouseClicked(MouseEvent e) throws IOException { 

      open folder %appdata% 
      // Open the folder in the file explorer not in Java. 
      // When I click on the button, the folder is viewed with the file explorer on the screen 
     } 
+0

是否要打開文件選擇器或系統文件資源管理器? – Vulcan

+0

我想在系統文件瀏覽器中打開 – Malasuerte94

+0

我在一個月前爲此寫了一個[FileExplorer class](http://textu.be/6)。我還發布了更詳細的答案。 – Vulcan

回答

3
import java.awt.Desktop; 
import java.io.File; 

public class OpenAppData { 

    public static void main(String[] args) throws Exception { 
     // Horribly platform specific. 
     String appData = System.getenv("APPDATA"); 
     File appDataDir = new File(appData); 
     // Get a sub-directory named 'texture' 
     File textureDir = new File(appDataDir, "texture"); 
     Desktop.getDesktop().open(textureDir); 
    } 
} 
+0

哇tnx :)和....如果我的路徑是%appdata%/紋理? – Malasuerte94

+0

+「\\ texture」我找到了:) – Malasuerte94

+0

我更喜歡使用編輯中顯示的第二個「File」構造函數,儘管它僅適用於Windows,但它並不重要。否則,爲該平臺找到一個環境變量,或者提供一個文件選擇器。 –

1

執行使用的Runtime.exec(..)的命令。但是,並非每個操作系統都具有相同的文件資源管理器,因此您需要處理操作系統。

的Windows:Explorer /select, file

的Mac:open -R file

Linux的:xdg-open file

我寫了一個FileExplorer類爲本地文件瀏覽器泄露文件的目的,但你需要編輯檢測操作系統。 http://textu.be/6

注意:這是如果你想透露個別文件。爲了顯示目錄,Desktop#open(File)要簡單得多,正如Andrew Thompson所發佈的那樣。

+0

您的http://textu.be/6的代碼不再可用。考慮將其重新發布到其他主機上或將其包含在您的答案中(或者從您的答案中刪除關於它的信息)。 – Pshemo

0

如果您使用的是Windows Vista和更高,System.getenv("APPDATA");將返回C:\Users\(username}\AppData\Roaming,所以你應該去一次了,並使用此路徑filechooser, 只是一個簡單的修改安德魯的例子,

String appData = System.getenv("APPDATA"); 
    File appDataDir = new File(appData); // TODO: this path should be changed! 
    JFileChooser fileChooser = new JFileChooser(appData); 
    fileChooser.showOpenDialog(new JFrame()); 

更多約windows xpwindows vista/7/8

相關問題