java - 如何在 JTextArea 中打开文件并使用 FileReader 和 FileWriter 类进行读写

标签 java swing jtextarea

我正在尝试在 JTextArea 中打开一个文件,然后对其进行写入和读取。我终于让它用 FileReader 在 JTextArea 中打开,然后试图合并 FileWriter 打破它。现在我无法再次在文本区域中打开它。我见过显示 FileChooser 打开特定文件的示例,但我希望用户能够传递一个变量,以便用户可以使用 FileChooser 打开他们浏览器的任何文件。当我破坏代码时,我在 OpenLister 方法中添加了一个文件阅读器。将 FileReader 和 FileWriter 放在同一个 ActionListener 中是常见的做法吗?任何关于一个好的例子和/或建议的方向将不胜感激。我已经复制了下面的代码。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class ClassChooser extends JFrame implements ActionListener
{
//create a label
private JLabel response;
File file;
//menu tabs
private JMenu fileMenu;
private JMenu editMenu;
private JMenu helpMenu;
String line;
//create a file chooser
private JFileChooser fc;
 BufferedReader br;
//create a text area
JTextArea ta = new JTextArea();

//constructors
public ClassChooser
{
    //create scroll pane
    JScrollPane scrollPane = new JScrollPane(ta);

    ta.setText("Enter text to see scroll bars.");
    //create a panel
    JPanel content = new JPanel();
    content.setLayout(new BorderLayout());
    content.add(scrollPane, BorderLayout.CENTER);

    //call functions to create drop down menu's 
    createFileMenu();
    createEditMenu();
    createHelpMenu();

    //create menu bar and add drop down menu's
    JMenuBar menuBar = new JMenuBar();
    this.setJMenuBar(menuBar);
    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    menuBar.add(helpMenu);


    this.setContentPane(content);
    this.setTitle("File Chooser");
    this.setVisible(true);
    this.setSize(600,250);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 }

public void createFileMenu()
{
    JMenuItem item;

    fileMenu = new JMenu("File");

    item = new JMenuItem("New");
    item.addActionListener(this);
    fileMenu.add(item);

    item = new JMenuItem("Open");
    item.addActionListener(new OpenListener());
    fileMenu.add(item);

    item =  new JMenuItem("Save");
    item.addActionListener(this);
    fileMenu.add(item);

    item = new JMenuItem("Rename");
    item.addActionListener(this);
    fileMenu.add(item);

    item = new JMenuItem("Delete");
    item.addActionListener(this);
    fileMenu.add(item);

    item = new JMenuItem("Make Directory");
    item.addActionListener(this);
    fileMenu.add(item);
    fileMenu.addSeparator();

    item = new JMenuItem("Exit");
    item.addActionListener(this);
    fileMenu.add(item);

}
public void createEditMenu()
{
    JMenuItem item;

    editMenu = new JMenu("Edit");

    item = new JMenuItem("Cut");
    item.addActionListener(this);
    editMenu.add(item);

    item = new JMenuItem("Copy");
    item.addActionListener(this);
    editMenu.add(item);

    item = new JMenuItem("Paste");
    item.addActionListener(this);
    editMenu.add(item);

}
public void createHelpMenu()
{
    JMenuItem item;

    helpMenu = new JMenu("Help");

    item = new JMenuItem("Welcome");
    item.addActionListener(this);
    helpMenu.add(item);

    item = new JMenuItem("Help Contents");
    item.addActionListener(this);
    helpMenu.add(item);
}

private class OpenListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{       
      fc = new JFileChooser();
      // directories only to be selected
      fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fc.setSelectedFile(fc.getCurrentDirectory() );
      fc.setDialogTitle("Directory Chooser");
      fc.setMultiSelectionEnabled(false);

      int retVal = fc.showOpenDialog(ClassChooser.this);
      //File file;

      if(retVal == fc.APPROVE_OPTION)
      {
         file = fc.getSelectedFile();

        try {
            br = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            line = br.readLine();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         while(line != null)
         {
             ta.append(line + "\n");
             try {
                line = br.readLine();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
         }
         }

  }
}

public static void main(String[] args)
{
   ClassChooser fce = new ClassChooser;
       String filename = File.separator + "tmp";

}

public void actionPerformed(ActionEvent e) 
{
// TODO Auto-generated method stub
 String menuName;

    menuName = e.getActionCommand();

    if(menuName.equals("Exit"))
    {
    System.exit(0);
    }
else
    {
    response.setText("Menu Item '" + menuName + "' is selected.");
    }   
}

}

最佳答案

您的代码实际上打开了该文件,但随后您在没有清除先前加载的文件的内容的情况下将其附加到文本区域中。

所以在您的 OpenListener类(class)actionPerformed方法添加 ta.setText("")作为第一条语句,然后继续加载文件内容。

代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class ClassChooser extends JFrame implements ActionListener {
   // create a label
   private JLabel           response;
   File                 file;
   // menu tabs
   private JMenu            fileMenu;
   private JMenu            editMenu;
   private JMenu            helpMenu;
   String                   line;
   // create a file chooser
   private JFileChooser fc = null; 
   BufferedReader           br;
   // create a text area
   JTextArea                ta  = new JTextArea();
     private String currentFileBeingEdited = null;
   // constructors
   public ClassChooser() {
       // create scroll pane
       JScrollPane scrollPane = new JScrollPane(ta);
       ta.setText("Enter text to see scroll bars.");
       // create a panel
       JPanel content = new JPanel();
       content.setLayout(new BorderLayout());
       content.add(scrollPane, BorderLayout.CENTER);
       // call functions to create drop down menu's
       createFileMenu();
       createEditMenu();
       createHelpMenu();
       // create menu bar and add drop down menu's
       JMenuBar menuBar = new JMenuBar();
       this.setJMenuBar(menuBar);
       menuBar.add(fileMenu);
       menuBar.add(editMenu);
       menuBar.add(helpMenu);
       this.setContentPane(content);
       this.setTitle("File Chooser");
       this.setVisible(true);
       this.setSize(600, 250);
       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

 public void createFileMenu() {
       JMenuItem item;
       fileMenu = new JMenu("File");
       item = new JMenuItem("New");
       item.addActionListener(this);
       fileMenu.add(item);
       item = new JMenuItem("Open");
       item.addActionListener(new OpenListener());
       fileMenu.add(item);
       item = new JMenuItem("Save");
       item.addActionListener(this);
       fileMenu.add(item);
       item = new JMenuItem("Rename");
       item.addActionListener(this);
       fileMenu.add(item);
       item = new JMenuItem("Delete");
       item.addActionListener(this);
       fileMenu.add(item);
       item = new JMenuItem("Make Directory");
       item.addActionListener(this);
       fileMenu.add(item);
       fileMenu.addSeparator();
       item = new JMenuItem("Exit");
       item.addActionListener(this);
       fileMenu.add(item);
 }

 public void createEditMenu() {
       JMenuItem item;
       editMenu = new JMenu("Edit");
       item = new JMenuItem("Cut");
       item.addActionListener(this);
       editMenu.add(item);
       item = new JMenuItem("Copy");
       item.addActionListener(this);
       editMenu.add(item);
       item = new JMenuItem("Paste");
       item.addActionListener(this);
       editMenu.add(item);
 }

public void createHelpMenu() {
    JMenuItem item;
    helpMenu = new JMenu("Help");
    item = new JMenuItem("Welcome");
    item.addActionListener(this);
    helpMenu.add(item);
    item = new JMenuItem("Help Contents");
    item.addActionListener(this);
    helpMenu.add(item);
    }

private class OpenListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        //ADDED ONLY THIS LINE
        ta.setText("");
        fc = new JFileChooser();
        // directories only to be selected
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setSelectedFile(fc.getCurrentDirectory());
        fc.setDialogTitle("Directory Chooser");
        fc.setMultiSelectionEnabled(false);

        int retVal = fc.showOpenDialog(ClassChooser.this);
        // File file;

        if (retVal == fc.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            currentFileBeingEdited = file.getAbsolutePath();
            try {
                br = new BufferedReader(new FileReader(file));
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                line = br.readLine();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            while (line != null) {
                ta.append(line + "\n");
                try {
                    line = br.readLine();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }

    }
}

public static void main(String[] args) {
    ClassChooser fce = new ClassChooser();
    String filename = File.separator + "tmp";

}

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    String menuName;

    menuName = e.getActionCommand();

    if (menuName.equals("Exit")) {
        System.exit(0);
    } else if("Save".equalsIgnoreCase(menuName)){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File(currentFileBeingEdited));
            pw.println(ta.getText());
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } finally {
            if(pw != null){
                pw.close();
            }
        }

    } else {
        response.setText("Menu Item '" + menuName + "' is selected.");
    }
}

}

关于java - 如何在 JTextArea 中打开文件并使用 FileReader 和 FileWriter 类进行读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8291246/

相关文章:

关闭终端实例后,JAVA_HOME 未设置/保存到路径变量

java - 使用 Point 类的示例?

java - 无法使用 ActionListener 访问 this.draw()

java - 如何将 JScrollPane 的滚动条放置在自定义位置?

java - java中ScrollPanel不出现JTextArea调整大小而是

java - 在运行时在 jtextArea 内添加随机单词,无需使用键盘

java - ArrayList<String> 插槽未使用 "set(int index, String value)"方法更新

java - 在一个 JPanel 上绘制 10 个线程

软件的 Java Swing GUI,最好的方法

java - 自动更新 Java Swing 应用程序的替代方法是什么?