话不多说先上代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.file.Files;
public class FileChooserDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("文件统计工具");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JPanel panel = new JPanel(new FlowLayout());
JLabel filePathLabel = new JLabel("选择文件:");
JTextField filePathField = new JTextField(20);
JButton chooseFileButton = new JButton("选择");
JTextArea resultArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(resultArea);
chooseFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
filePathField.setText(selectedFile.getAbsolutePath());
try {
String content = new String(Files.readAllBytes(selectedFile.toPath()));
int digitsCount = 0;
int lettersCount = 0;
int punctuationsCount = 0;
for (char c : content.toCharArray()) {
if (Character.isDigit(c)) {
digitsCount++;
} else if (Character.isLetter(c)) {
lettersCount++;
} else if (String.valueOf(c).matches("[!\"#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~]")) {
punctuationsCount++;
}
}
resultArea.setText("数字总数: " + digitsCount + "\n"
+ "字母个数: " + lettersCount + "\n"
+ "英文标点个数: " + punctuationsCount + "\n"
+ "字符总数: " + content.length());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
panel.add(filePathLabel);
panel.add(filePathField);
panel.add(chooseFileButton);
panel.add(scrollPane);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
小儿科代码没什么好说的