java讀取文本到文本編輯框如何弄

小億
86
2024-01-18 19:47:13

要將文本讀取到Java的文本編輯框中,可以使用Swing框架中的JTextArea組件。以下是一個(gè)示例代碼:

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();
    }
}

運(yùn)行以上代碼,將會(huì)顯示一個(gè)窗口,點(diǎn)擊"Open File"按鈕可以選擇要讀取的文本文件,然后將文件內(nèi)容顯示在文本編輯框中。

0