【发布时间】:2009-03-19 12:05:09
【问题描述】:
我是 Swing 新手,希望在我的 Swing 代码中实现下载文件功能,这将允许用户保存或打开特定文件。
我确实看过 JFileChooser.showOpenDialog 和 showSaveDialog,但我不想使用它,因为它让我可以从文件系统中选择任何文件。
希望我的问题很清楚。请帮我解决这个问题。
【问题讨论】:
我是 Swing 新手,希望在我的 Swing 代码中实现下载文件功能,这将允许用户保存或打开特定文件。
我确实看过 JFileChooser.showOpenDialog 和 showSaveDialog,但我不想使用它,因为它让我可以从文件系统中选择任何文件。
希望我的问题很清楚。请帮我解决这个问题。
【问题讨论】:
您想使用它们,并添加一个过滤器。例如:
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("jpg");
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
这只会显示 JPG 和 GIF 文件。从here窃取的示例
编辑:你知道 ExampleFileFilter 实现了抽象类FileFilter
编辑:由于您知道文件的名称,因此您可以只使用一个打开按钮并使用 Runtime.getRuntime.exec('the file to beopen.doc") 并且应该在适当的应用。
为了保存,您仍然需要提示他们找出他们想要保存它的位置,因此您仍然需要 JFileChooser。我仍然会使用过滤器,并在必要时动态确定文件扩展名,然后执行:
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
String selectedFile = "The suggested save name.";
chooser.setSelectedFile(selectedFile);
ExampleFileFilter filter = new ExampleFileFilter();
String extension = "Do something to find your extension";
filter.addExtension(extension);
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
//then write your code to write to disk
}
希望对您有所帮助。
【讨论】:
您可以将过滤器添加到文件选择器。很容易实现你自己的,它只接受你允许的文件。
选择文件后,您需要自己实现文件的保存/读取。桌面应用程序中没有下载/上传之类的东西。
【讨论】: