温馨提示×

java读取文本到文本编辑框如何弄

小亿
86
2024-01-18 19:47:13
栏目: 编程语言

要将文本读取到Java的文本编辑框中,可以使用Swing框架中的JTextArea组件。以下是一个示例代码:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileReadExample extends JFrame {

    private JTextArea textArea;
    private JButton openButton;

    public FileReadExample() {
        textArea = new JTextArea();
        openButton = new JButton("Open File");

        openButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files", "txt");
                fileChooser.setFileFilter(filter);

                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    try {
                        FileReader fileReader = new FileReader(fileChooser.getSelectedFile());
                        BufferedReader reader = new BufferedReader(fileReader);
                        String line;
                        StringBuilder sb = new StringBuilder();
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                            sb.append("\n");
                        }
                        reader.close();
                        textArea.setText(sb.toString());
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Error reading file: " + ex.getMessage());
                    }
                }
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(openButton);

        JScrollPane scrollPane = new JScrollPane(textArea);

        getContentPane().add(buttonPanel, BorderLayout.NORTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setVisible(true);
    }

    public static void main(String[] args) {
        new FileReadExample();
    }
}

运行以上代码,将会显示一个窗口,点击"Open File"按钮可以选择要读取的文本文件,然后将文件内容显示在文本编辑框中。

0