Java 如何使用 JFileChooser 保存文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2531037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:54:01  来源:igfitidea点击:

How to save file using JFileChooser?

javaswingbufferedimagejfilechooserfilefilter

提问by Lokesh Kumar

I have a method in my application called "Save as" which Saves the image of my application on computer my into a file. I used the JFileChooser to let the users choose their desired location for saving the file. The problem is unless user explicitly types in the file format, it saves the file with no extension. How can I have formats like jpg, png in the File Type drop down menu.

我的应用程序中有一个名为“另存为”的方法,它将我的应用程序在计算机上的图像保存到一个文件中。我使用 JFileChooser 让用户选择他们想要保存文件的位置。问题是除非用户明确输入文件格式,否则它会保存没有扩展名的文件。如何在“文件类型”下拉菜单中使用 jpg、png 等格式。

and, how can i get extension from the File Type drop menu for saving my image file.

以及,如何从文件类型下拉菜单中获取扩展名以保存我的图像文件。

 ImageIO.write(image,extension,file);

采纳答案by Lokesh Kumar

Finally, I solved my own problem:

最后,我解决了我自己的问题:

JFileChooser fc = new JFileChooser("C:/");
fc.addChoosableFileFilter(new JPGSaveFilter());
fc.addChoosableFileFilter(new JPEGSaveFilter());
fc.addChoosableFileFilter(new PNGSaveFilter());
fc.addChoosableFileFilter(new GIFSaveFilter());
fc.addChoosableFileFilter(new BMPSaveFilter());
fc.addChoosableFileFilter(new WBMPSaveFilter()); 

int retrieval = fc.showSaveDialog(null);

if (retrieval == JFileChooser.APPROVE_OPTION) {
  String ext = "";

  String extension = fc.getFileFilter().getDescription();

  if (extension.equals("*.jpg,*.JPG")) {
    ext = ".jpg";
  } else if (extension.equals("*.png,*.PNG")) {
    ext = ".png";
  } else if (extension.equals("*.gif,*.GIF")) {
    ext = ".gif";
  } else if (extension.equals("*.wbmp,*.WBMP")) {
    ext = ".wbmp";
  } else if (extension.equals("*.jpeg,*.JPEG")) {
    ext = ".jpeg";
  } else if (extension.equals("*.bmp,*.BMP")) {
    ext = ".bmp";
  }
}

Example Filter:

示例过滤器:

package example

import java.io.File;
import javax.swing.filechooser.FileFilter;

class JPGSaveFilter extends FileFilter {
  @Override
  public boolean accept(File f) {
    if (f.isDirectory()) {
      return false;
    }

    String s = f.getName().toLowerCase();

    return s.endsWith(".jpg");
  }

  @Override
  public String getDescription() {
    return "*.jpg,*.JPG";
  }
}

回答by Daniel De León

Prepare the file chooser filters:

准备文件选择器过滤器:

    jFileChooser.addChoosableFileFilter(new FileNameExtensionFilter("File X (.xxx)", "xxx"));
    jFileChooser.addChoosableFileFilter(new FileNameExtensionFilter("File Y (.yyy)", "yyy"));
    jFileChooser.addChoosableFileFilter(new FileNameExtensionFilter("File Z (.zzz)", "zzz"));

    // set default type
    jFileChooser.setFileFilter(jFileChooser.getChoosableFileFilters()[0]);

    // set default file
    jFileChooser().setSelectedFile(defaultFile);

After approve validation

批准确认后

//Add extension to Selected file 
File file = new File(jFileChooser().getSelectedFile().getCanonicalPath() + "." + ((FileNameExtensionFilter) jFileChooser().getFileFilter()).getExtensions()[0]);

Could be a good idea validate if the selected file come with extension.

验证所选文件是否带有扩展名可能是一个好主意。

回答by kcpr

I think I got better solution. Will explain it with sample code fragments.

我想我得到了更好的解决方案。将用示例代码片段解释它。

This is how I set file filter:
jFileChooser.setFileFilter(new FileNameExtensionFilter(".txt", "txt"));.

这就是我设置文件过滤器的方式:
jFileChooser.setFileFilter(new FileNameExtensionFilter(".txt", "txt"));.

After this the main saving line:
textArea1.write(new BufferedWriter(new FileWriter(jFileChooser.getSelectedFile().getAbsolutePath() + jFileChooser.getFileFilter().getDescription().replace("All Files", ""))));.

在此之后,主保存行:
textArea1.write(new BufferedWriter(new FileWriter(jFileChooser.getSelectedFile().getAbsolutePath() + jFileChooser.getFileFilter().getDescription().replace("All Files", ""))));

Of course the most important is this fragment: jFileChooser.getSelectedFile().getAbsolutePath() + jFileChooser.getFileFilter().getDescription().replace("All Files", "").

当然最重要的是这个片段: jFileChooser.getSelectedFile().getAbsolutePath() + jFileChooser.getFileFilter().getDescription().replace("All Files", "").

The only thing I don't like is, that I could not find any method like 'getExtension' which means that You cannot have any nice description without unnecessary troubles with strings.

我唯一不喜欢的是,我找不到任何像“getExtension”这样的方法,这意味着如果没有字符串不必要的麻烦,你就不能有任何好的描述。



Ok, got it. You can do something like that: jFileChooser.getFileFilter().toString().replaceFirst(".*extensions=\\[(.*)]]", ".$1").replaceFirst(".*AcceptAllFileFilter.*", "").

好的,我知道了。你可以做这样的事情: jFileChooser.getFileFilter().toString().replaceFirst(".*extensions=\\[(.*)]]", ".$1").replaceFirst(".*AcceptAllFileFilter.*", "")

Unfortunately it's not so beautiful, but seems to work like a charm.

不幸的是,它不是那么漂亮,但似乎很有魅力。