java JFileChooser File Size Filter

丶灬走出姿态 提交于 2019-12-19 12:03:14

问题


I know I can make a filter by file type, but is it possible to filter by file size?

For example a JFileChooser to show only pictures within 3 MegaBytes.


回答1:


The short answer should be, what have you tried? The long answer is yes...

JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new FileFilter() {

    @Override
    public boolean accept(File f) {
        String name = f.getName().toLowerCase();
        return (name.endsWith(".png") &&
                        name.endsWith(".jpg") &&
                        name.endsWith(".gif") &&
                        name.endsWith(".bmp") &&
                        f.length() < 3 * (1024 * 1024));
    }

    @Override
    public String getDescription() {
        return "Images < 3mb";
    }
});

Technically, you can filter on any property or combination of properties from File




回答2:


Create a sub-class of FileFilter. In the accept method, decide if the file is too large or not.

public boolean accept(File f) {
    if(f.length() > maxSize) return false;
    return true;
}

Then apply the filter to your File Chooser



来源:https://stackoverflow.com/questions/28667457/java-jfilechooser-file-size-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!