2012-06-10 64 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

相关问题