Home >Java >javaTutorial >How to find and replace content in a file in Java?

How to find and replace content in a file in Java?

WBOY
WBOYforward
2023-04-20 22:31:071172browse

1. Question description - Find files of a specified type

1. Question

Title: In the operating system, different types of files are distinguished by their file extensions. List the file name, file size and modification time of files of this type in the specified folder based on the extension entered by the user.

2. Problem-solving ideas

Create a class: FilesList

The FilesList class inherits JFrame and uses the form as the interface.

There is an input text box for entering the file extension

There is a "Select Folder" button. After clicking, the program will first determine whether the entered file extension is empty. If it is empty, prompt: Please enter the file type. If not empty, use the entered file extension to filter files in the folder selected by the user and display them on the interface.

The filtering method is to use the listFiles method of the File class to filter

3. Detailed code explanation

package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre class="brush:php;toolbar:false">
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/2.1	    xiaoxuzhu		2022/5/2		    Create
 * 
 * @date 2022/5/2  */ public class FilesList extends JFrame {     /**      *      */     private static final long serialVersionUID = -2029566581047632579L;     private JPanel contentPane;     private JTextField textField;     private JTable table;     /**      * Launch the application.      */     public static void main(String[] args) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 try {                     FilesList frame = new FilesList();                     frame.setVisible(true);                 } catch (Exception e) {                     e.printStackTrace();                 }             }         });     }     /**      * Create the frame.      */     public FilesList() {         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setBounds(100, 100, 450, 300);         contentPane = new JPanel();         contentPane.setLayout(new BorderLayout(0, 0));         setContentPane(contentPane);         JPanel panel = new JPanel();         contentPane.add(panel, BorderLayout.NORTH);         JLabel label = new JLabel("输入文件扩展名:");         label.setFont(new Font("微软雅黑", Font.PLAIN, 15));         panel.add(label);         textField = new JTextField();         textField.setFont(new Font("微软雅黑", Font.PLAIN, 15));         panel.add(textField);         textField.setColumns(12);         JButton button = new JButton("选择文件夹");         button.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent e) {                 do_button_actionPerformed(e);             }         });         button.setFont(new Font("微软雅黑", Font.PLAIN, 15));         panel.add(button);         JScrollPane scrollPane = new JScrollPane();         contentPane.add(scrollPane, BorderLayout.CENTER);         table = new JTable();         JTableHeader header = table.getTableHeader();         header.setFont(new Font("微软雅黑", Font.PLAIN, 15));         header.setPreferredSize(new Dimension(header.getWidth(), 25));// 修改表头的高度         table.setFont(new Font("微软雅黑", Font.PLAIN, 13));         table.setRowHeight(25);         DefaultTableModel model = (DefaultTableModel) table.getModel();         model.setColumnIdentifiers(new String[] { "文件名", "文件大小", "修改时间" });         scrollPane.setViewportView(table);     }     protected void do_button_actionPerformed(ActionEvent e) {         final String fileType = textField.getText();// 获得用户输入的文件类型         if (fileType.isEmpty()) {// 提示用户输入文件类型             JOptionPane.showMessageDialog(this, "请输入文件类型!", "", JOptionPane.WARNING_MESSAGE);             return;         }         JFileChooser chooser = new JFileChooser();// 创建文件选择器         chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);// 设置仅能选择文件夹         chooser.setMultiSelectionEnabled(false);// 禁止选择多个文件夹         int result = chooser.showOpenDialog(this);// 打开文件选择器         if (result == JFileChooser.APPROVE_OPTION) {             File[] listFiles = chooser.getSelectedFile().listFiles(new java.io.FileFilter() {                 @Override                 public boolean accept(File pathname) {                     if (pathname.getName().toLowerCase().endsWith(fileType.toLowerCase())) {                         return true;                     } else {                         return false;                     }                 }             });// 获得符合条件的文件             table.removeAll();             DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得默认表格模型                          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 指定日期格式             for (File file : listFiles) {                 String name = file.getName();// 获得文件名                 long size = file.length();// 获得文件大小                 String modifyDate = format.format(new Date(file.lastModified()));// 获得文件修改日期                 model.addRow(new String[] { name, "" + size, modifyDate });// 向表格中增加数据             }             table.setModel(model);// 更新表格模型         }     } }

How to find and replace content in a file in Java?

How to find and replace content in a file in Java?

4. Learn one more knowledge point

To change a string into a lowercase string, you can use the function

toLowerCase().

Usage

String fileType = "MD";
fileType = fileType.toLowerCase();//获取小写的字符串

2. Question description-Use Tree structure display path

1. Question

Question: The operating system mainly manages files in a tree structure. Use JAVA's tree control to display the file structure.

2. Problem-solving ideas

Create a class: FilesTree

The FilesList class inherits JFrame and uses the form as the interface.

Add a JTree control using JFrame

Add a system file root for the JTree control

The system file root can be obtained using the listRoots() method of File.

3. Detailed code explanation

package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;
import java.io.FileFilter;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre class="brush:php;toolbar:false">
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/2.1	    xiaoxuzhu		2022/5/2		    Create
 * 
 * @date 2022/5/2  */ public class FilesTree extends JFrame {     /**      *      */     private static final long serialVersionUID = -2055459510450224221L;     private JPanel contentPane;     private JTree tree;     /**      * Launch the application.      */     public static void main(String[] args) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 try {                     FilesTree frame = new FilesTree();                     frame.setVisible(true);                 } catch (Exception e) {                     e.printStackTrace();                 }             }         });     }     /**      * Create the frame.      */     public FilesTree() {         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setBounds(100, 100, 450, 300);         contentPane = new JPanel();         contentPane.setLayout(new BorderLayout(0, 0));         setContentPane(contentPane);         JScrollPane scrollPane = new JScrollPane();         contentPane.add(scrollPane, BorderLayout.CENTER);         File[] disks = File.listRoots();// 获得所有可用的文件系统根         DefaultMutableTreeNode root = new DefaultMutableTreeNode();// 创建节点         for (File disk : disks) {// 将File数组中的元素增加到节点上             root.add(new DefaultMutableTreeNode(disk));         }         tree = new JTree(root);// 使用节点创建树控件         tree.addTreeSelectionListener(new TreeSelectionListener() {             public void valueChanged(TreeSelectionEvent e) {                 do_tree_valueChanged(e);             }         });         scrollPane.setViewportView(tree);     }     protected void do_tree_valueChanged(TreeSelectionEvent e) {         // 获得用户选择的节点         DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();         File selectFile = (File) selectNode.getUserObject();// 获得节点代表的File类型对象         if (selectFile.isDirectory()) {// 如果File类型对象是文件夹             File[] files = selectFile.listFiles(new FileFilter() {                 @Override                 public boolean accept(File pathname) {// 过滤掉隐藏类型文件                     if (pathname.isHidden()) {                         return false;                     } else {                         return true;                     }                 }             });             for (File file : files) {// 将符合条件的File类型对象增加到用户选择的节点中                 selectNode.add(new DefaultMutableTreeNode(file));             }         } else {             return;         }     } }

How to find and replace content in a file in Java?

Double-click to expand the folder

How to find and replace content in a file in Java?

3. Question description -Find and replace file content

1. Question

Question: You can replace the file content without opening the file.

2. Problem-solving ideas

Create a class: ReplaceTool

The ReplaceTool class inherits JFrame and uses the form as the interface.

There are two input boxes: the string before replacement and the string after replacement

Create a select file button to select which file to replace

Create a start replacement button, Replace according to the content of the input box

The function used to replace the string is the replace method of the String class

3. Detailed code explanation

Use pom and introduce the htuool package. Mainly use this tool method: IoUtil.read, used to read the contents of the file.

  <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-core</artifactId>
            <version>5.6.5</version>
        </dependency>
rrree

How to find and replace content in a file in Java?

Text content before replacement

How to find and replace content in a file in Java?

How to find and replace content in a file in Java?

How to find and replace content in a file in Java?

How to find and replace content in a file in Java?

The above is the detailed content of How to find and replace content in a file in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete