我已经制作了一个按钮,但我现在不知道如何让它打开一个特定的目录,例如单击按钮时%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
}
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);
}
}
使用 Runtime.exec(..) 执行命令。 但是,并非每个操作系统都有相同的文件资源管理器,因此您需要处理操作系统。
窗户: Explorer /select, file
苹果:open -R file
Linux: xdg-open file
我编写了一个文件资源管理器类,目的是在本机文件资源管理器中显示文件,但您需要对其进行编辑以检测操作系统。http://textu.be/6
注意:这是如果您希望显示单个文件。 要显示目录,Desktop#open(File)
要简单得多,正如Andrew Thompson发布的那样。
如果您使用的是Windows Vista及更高版本,System.getenv("APPDATA");
将返回C:Users(username}AppDataRoaming
,因此您应该向上走一次,并将此路径用于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 XP 和 Windows vista/7/8 的更多信息