As a unit that stores data, files will generate many categories according to the data type, which is the so-called file type. When operating data files, different processing is often required according to different file types. This example implements reading files of the specified type of folder and displaying them into table controls. This plays a role in attracting the classification of files in project development.
Idea Analysis:
Because it is a form application, first look at the view layer. A button control JButton is needed to select a folder; a tag control JLabel is needed to display the selected path; a tag control JLabel is needed to prompt the user to enter what to enter; a text box control JTextField is needed for the user to enter the file type; a table control JTable is needed Displays the file of the specified type in the selected directory.
For button controls, bind event processing methods to them. In this method, first create a JFileChooser file selector object and set a filter for the selector, that is, use the setFileSelectionMode() method of the JFileChoos class to set only the path to select. Then execute the showDialog() method, then use the getSelectedFile() method of the JFileChooser class to get the selected path, assign it to a File type variable, use the toString() method to display the path in the label, and finally get the filtered file array that meets the conditions. .
For text box controls, once the text inside changes, the file in the selected path needs to be refiltered. Therefore, the event processing method is bound to the JTextField class addCaretListener() method, and the filtered conformance is obtained in this method Array of files for conditions.
Because both the button control and the text box control must implement filtering and display, filtering and display can be used as a separate method. In this method, first determine whether the current path is empty. If it is not empty, use the listFiles() method of the File class Get the file array that meets the conditions, assign the value to a File-type array, and then use the getModel() method of the JTable class to get the data model of the table, and use the setRow of the DefaultTableModel class to get the data model. The Count() method first clears the table, then loops through the file array using foreach(), creates table row data using the Object[] array in the loop, calls the getName() method of the File class to get the file name, and the length() method to get the file Size, lastModified() method gets the modification date, and finally use the addRow() method of the DefaultTableModel class to add row data to the tabular model.
The code is as follows:
The code copy 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;
/**
* Custom extension filter
*
* @author Li Zhongwei
*/
private final class CustomFilter implements java.io.FileFilter {
@Override
public boolean accept(File pathname) {
// Get 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;// Complete 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;
/**
* Launch the application.
*/
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();
}
}
});
}
/**
* Create the frame.
*/
public ListCustomTypeFile() {
setTitle("Show 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 careUpdate(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[] {"File Name", "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);
}
/**
* Select the event handling method of folder button
*
* @param e
*/
protected void do_button_actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();// Create a file selector
// Set the filter for selector
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showDialog(this, null);
dir = chooser.getSelectedFile();
getLabel().setText(dir.toString());
// Get the filtered file array that meets the criteria
listFiles();
}
/**
* Show files in the folder
*/
private void listFiles() {
if (dir == null)
return;
// Get the file array that meets the criteria
File[] files = dir.listFiles(new CustomFilter());
// Get the data model of the table
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
for (File file : files) {// traverse the file array
// Create table row data
Object[] row = { file.getName(), file.length(),
new Date(file.lastModified()) };
model.addRow(row);// Add row data to the tabular model
}
}
protected void do_extNameField_caretUpdate(CaretEvent e) {
listFiles();
}
protected JLabel getLabel() {
return label;
}
}
The effect is shown in the picture: