给出在文件选择器或文件对话框中获取当前日期或请求日期文件的示例代码?我需要在文件对话框中过滤带有日期的文件?
问问题
620 次
1 回答
1
首先,我不确定是否存在使用日期的现有文件过滤器,所以对我来说最好和快速的解决方案是实现我自己的过滤器:
public class DateFileFilter extends FileFilter
{
public boolean accept(File file)
{
GregorianCalendar date = new GregorianCalendar();//I get the today value
GregorianCalendar fileDate = new GregorianCalendar();
fileDate.setTimeInMillis(file.lastModified());//Here I get date info of the file
//Compare the current month and year
//with the month and yearthe file was
//last modified
return (((date.get(GregorianCalendar.MONTH) ==
fileDate.get(GregorianCalendar.MONTH)) &&
(date.get(GregorianCalendar.YEAR) ==
fileDate.get(GregorianCalendar.YEAR))) ||
file.isDirectory());
}
public String getDescription()
{
return "This is my filter for dates (:";
}
}
然后您可以将过滤器添加到 JFileChooser:
JFileChooser jf = new JFileChooser();
jf.setFileFilter(/*HERE MY DATE FILTER*/);
对于文件对话框,过程应该类似:
DateFileFilter filter = new DateFileFilter();
FileDialog dialog = new FileDialog(parent, "Choose File");
dialog.setFilenameFilter(filter);
dialog.show();
String selectedFile = dialog.getFile();
但我认为您也可以实现“过滤器”接口而不是“扩展”。
希望它有所帮助,最好的问候(:
于 2013-04-03T05:47:06.940 回答