尝试将文本文件读入JTextArea

时间:2013-07-06 03:34:48

标签: java windows swing io jtextarea

我尝试打开文本文件并将其值添加到String变量中,然后设置为JTextArea。无论我做什么,它总是在textarea中什么都不返回。 我希望它像按下清除按钮时一样更改文本,但我想将其更改为它所生成的Test.txt文件中的内容。

package texteditor;

import java.awt.FlowLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class GUI extends JFrame {
    //GUI Variables

    private JButton save;
    private JButton clear;
    private JButton copy;
    private JButton paste;
    private JButton open;
    private JTextArea textField;
    private StringSelection stringSelection;
    private Clipboard clipboard;
    String textFieldWritable;

    public GUI() {
        super("Text Editor");
        //Sets Layout
        setLayout(new FlowLayout());

        save = new JButton("Save");
        add(save);
        clear = new JButton("Clear");
        add(clear);
        open = new JButton("Open");
        add(open);


        textField = new JTextArea(10, 35);
        add(textField);

        handler handle = new handler();

        save.addActionListener(handle);
        clear.addActionListener(handle);

    }

    private class handler implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (event.getSource() == save) {
                textFieldWritable = String.format("%s", textField.getText());
                try {
                    FileWriter fileWrite = new FileWriter("Text.txt");
                    PrintWriter printWrite = new PrintWriter(fileWrite);

                    printWrite.println(textFieldWritable);
                    printWrite.close();
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null,
                        "Error, File Already Exists!", "Error",
                        JOptionPane.ERROR_MESSAGE);
                }
            } else if (event.getSource() == clear) {
                textField.setText("");
            } else if (event.getSource() == open) {
                try {
                    FileReader fileReader = new FileReader("Text.txt");
                    BufferedReader bufferedReader = new BufferedReader(fileReader);

                    String inputFile = "";
                    String textFieldReadable = bufferedReader.readLine();

                    while (textFieldReadable != null) {
                        inputFile += textFieldReadable;
                        textFieldReadable = bufferedReader.readLine();
                    }
                    System.out.println("inputFile");
                } catch (FileNotFoundException ex) {
                    System.out.println("no such file exists");
                } catch (IOException ex) {
                    System.out.println("unkownerror");
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

对我来说,看起来你从未将你读过的文字设置到文本区域。

try {
    FileReader fileReader = new FileReader("Text.txt");
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    String inputFile = "";
    String textFieldReadable = bufferedReader.readLine();

    while (textFieldReadable != null){
        inputFile += textFieldReadable;
        textFieldReadable = bufferedReader.readLine();                    
    }
    System.out.println("inputFile");
    // Opps //
    textField.setText(inputFile);

}
catch (FileNotFoundException ex) {
    System.out.println("no such file exists");
}
catch (IOException ex) {
    System.out.println("unkownerror");
}

就个人而言,我只使用JTextComponent提供的功能并将其传递给Reader并允许其自行阅读。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TextAreaReadTest {

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

    public TextAreaReadTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextArea textArea;

        public TestPane() {
            setLayout(new BorderLayout());
            textArea = new JTextArea(10, 80);
            add(new JScrollPane(textArea));
            JButton read = new JButton("Read");
            read.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reader reader = null;
                    try {
                        reader = new FileReader(new File("D:/SWANH.txt"));
                        textArea.read(reader, "The force is strong with this one");
                    } catch (Exception exp) {
                        exp.printStackTrace();
                    } finally {
                        try {
                            reader.close();
                        } catch (Exception exp) {
                        }
                    }
                }
            });
            add(read, BorderLayout.SOUTH);
        }

    }

}

答案 1 :(得分:0)

此代码为我工作

    public DisplayText() throws IOException {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    textArea.setBounds(15, 13, 424, 210);
    textArea.setEditable(false);
    contentPane.add(textArea);

    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBounds(12, 12, 424, 185);
    contentPane.add(scrollPane);

    JButton btnPatchDetails = new JButton("Details");
    btnPatchDetails.setBounds(135, 234, 137, 25);
    contentPane.add(btnPatchDetails);

    btnPatchDetails.addActionListener(this);
    btnPatchDetails.setActionCommand("Patch Details");

    JButton btnNext = new JButton("Next");
    btnNext.setBounds(314, 234, 107, 25);
    contentPane.add(btnNext);

    JLabel lblDependancyPatchAvailable = new JLabel("Dependancy Patch Available : ");
    lblDependancyPatchAvailable.setBounds(22, 209, 220, 15);
    contentPane.add(lblDependancyPatchAvailable);

    lblAvailability.setBounds(254, 209, 61, 15);
    contentPane.add(lblAvailability);
}

public void actionPerformed(ActionEvent e) {
    if ("Patch Details".equals(e.getActionCommand())) {
        BufferedReader reader = null;
        JarFile jarFile = null;
        try {

            String inputFile = "readMe/tempReadme.txt";
            String write;   

          jarFile = new JarFile(inputJar);
               JarEntry entry = jarFile.getJarEntry(inputFile);

               reader = new BufferedReader(new InputStreamReader(jarFile.getInputStream(entry)));
               String line,searchStr = "Patch Details",endStr = "Problem:";
               boolean readFlag = false;
               boolean writeFlag = false;

               while ((line = reader.readLine()) != null) {

                  if (line.trim().contains(searchStr)) {
                      readFlag = true;
                    }

                    if (line.trim().equals(endStr)) {
                        break;
                    }

                    if (readFlag) {
                        StringTokenizer tempTokenizer = new StringTokenizer(line,"");
                        while (tempTokenizer.hasMoreElements()) {
                            write = tempTokenizer.nextToken();
                        textArea.append(write + "\n");
                        }
                     }
                    writeFlag = true;
              } 
               if(writeFlag){
                   lblAvailability.setText("YES");
               } else {
                   lblAvailability.setText("");
               }

               lblAvailability.getText();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {

                try {
                    jarFile.close();
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
    }