The Java implementation displays the file of the specified type

  • 2020-04-01 03:02:23
  • OfStack

As a unit for storing data, files generate many categories by data type, which is called file type. When operating on data files, it is often necessary to do different processing according to different file types. This example implements reading a file of the specified type of folder and displaying it in a table control. This has played a role in the document classification of the project development.

Thought analysis:

Because it's a form application, look at the view layer first. A button control JButton is needed to select a folder. A label control, JLabel, is needed to display the selected path. A label control, JLabel, is required to prompt the user for what to enter. Need a text box control JTextField for the user to enter a file type; You need a table control, JTable, to display files of the specified type in the selected directory.
For button controls, for its binding event processing method, in this method, first create JFileChooser File selector object, set the selector for the object of the filter, namely by JFileChoose setFileSelectionMode set () method can only choose the path, then execute the showDialog () method, then use getSelectedFile JFileChooser class () method to get selected path, assign a value to a variable File type, Use the toString() method to display the path in the label and finally get the filtered array of qualified files.
For the textbox control, once the text inside changes, the files in the selected path need to be filtered again, so the addCaretListener () method of the JTextField class is used to bind the event handling method for it, and the filtered array of qualified files is obtained in this method.
Because the button control and a text box control and display, to achieve filtering can filter and display individual as a method, in this method first determines whether the current path is empty, if not null using the File type of listFiles () method to obtain qualified File an array, assign a value to a File type array, and then use the data type of getModel () method to obtain the form of data model, using DefaultTableModel class setRowCount () method to empty form, Then loop through the File array using foreach(), create the table row data using the Object[] array in the loop, call the getName() method of the File class to get the File name, the length() method to get the File size, the lastModified() method to get the modified date, and finally use the addRow () method of the DefaultTableModel class to add the row data to the table model.
The code is as follows:


import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.table.DefaultTableModel;

public class ListCustomTypeFile extends JFrame {
    
    private static final long serialVersionUID = -6263975104443132420L;

    
    private final class CustomFilter implements java.io.FileFilter {
        @Override
        public boolean accept(File pathname) {
            //Gets the specified extension set by the user
            String extName = extNameField.getText();
            if (extName == null || extName.isEmpty())
                return false;
            if (!extName.startsWith("."))//Determine the extension prefix
                extName = "." + extName;//Completion extension prefix
            extName = extName.toLowerCase();
            //Determine whether the extension and filter file name meet the requirements
            if (pathname.getName().toLowerCase().endsWith(extName))
                return true;
            return false;
        }
    }

    private JPanel contentPane;
    private JTextField extNameField;
    private JTable table;
    private File dir;
    private JLabel label;

    
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ListCustomTypeFile frame = new ListCustomTypeFile();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    
    public ListCustomTypeFile() {
        setTitle(" Displays the file of the specified type ");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[] { 93, 54, 0 };
        gbl_panel.rowHeights = new int[] { 23, 0, 0 };
        gbl_panel.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
        gbl_panel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
        panel.setLayout(gbl_panel);

        JButton button = new JButton(" Select folder ");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button_actionPerformed(e);
            }
        });
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.anchor = GridBagConstraints.NORTH;
        gbc_button.gridx = 0;
        gbc_button.gridy = 0;
        panel.add(button, gbc_button);

        label = new JLabel(" folder ");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.fill = GridBagConstraints.HORIZONTAL;
        gbc_label.gridx = 1;
        gbc_label.gridy = 0;
        panel.add(label, gbc_label);

        JLabel label_1 = new JLabel(" Enter the specified file extension name: ");
        GridBagConstraints gbc_label_1 = new GridBagConstraints();
        gbc_label_1.anchor = GridBagConstraints.EAST;
        gbc_label_1.insets = new Insets(0, 0, 0, 5);
        gbc_label_1.gridx = 0;
        gbc_label_1.gridy = 1;
        panel.add(label_1, gbc_label_1);

        extNameField = new JTextField();
        extNameField.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                do_extNameField_caretUpdate(e);
            }
        });
        extNameField.setText(".gif");
        GridBagConstraints gbc_extNameField = new GridBagConstraints();
        gbc_extNameField.insets = new Insets(0, 0, 5, 0);
        gbc_extNameField.fill = GridBagConstraints.HORIZONTAL;
        gbc_extNameField.gridx = 1;
        gbc_extNameField.gridy = 1;
        panel.add(extNameField, gbc_extNameField);
        extNameField.setColumns(10);

        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        table = new JTable();
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setModel(new DefaultTableModel(new Object[][] {}, new String[] {" The file name ", " The file size "," Modification date " }) {
            
                    private static final long serialVersionUID = 5274214559103654856L;
            boolean[] columnEditables = new boolean[] { false, false, false };

            public boolean isCellEditable(int row, int column) {
                return columnEditables[column];
            }
        });
        table.getColumnModel().getColumn(0).setPreferredWidth(220);
        table.getColumnModel().getColumn(1).setPreferredWidth(85);
        table.getColumnModel().getColumn(2).setPreferredWidth(110);
        scrollPane.setViewportView(table);
    }

    
    protected void do_button_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();//Create a file selector
        //Sets the filter for the selector
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.showDialog(this, null);
        dir = chooser.getSelectedFile();
        getLabel().setText(dir.toString());
        //Gets the filtered array of qualified files
        listFiles();
    }

    
    private void listFiles() {
        if (dir == null)
            return;
        //Gets an array of qualified files
        File[] files = dir.listFiles(new CustomFilter());
        //Gets the data model for the table
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);
        for (File file : files) {//Traverses the array of files
            //Create table row data
            Object[] row = { file.getName(), file.length(),
                    new Date(file.lastModified()) };
            model.addRow(row);//Add row data to the table model
        }
    }

    protected void do_extNameField_caretUpdate(CaretEvent e) {
        listFiles();
    }

    protected JLabel getLabel() {
        return label;
    }
}

The effect is as follows:
< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201403/201431153244086.png" >


Related articles: