【问题标题】:Save a the text from a jTextArea (ie Save As) into a new .txt file将 jTextArea 中的文本(即另存为)保存到新的 .txt 文件中
【发布时间】:2012-03-13 19:26:23
【问题描述】:

我正忙于将文字处理器作为我的项目之一,我需要将输入到 jTextArea 中的文本保存为 .txt 文件,其中包含用户选择的名称和位置。注意“fc”是我已经声明的文件选择器的名称。

   public class TextEditor extends javax.swing.JFrame {

    int count = 2;
    JTextArea n = new JTextArea();
    final JFileChooser fc = new JFileChooser();

    public void SaveAs() {

        final JFileChooser SaveAs = new JFileChooser();
        SaveAs.setApproveButtonText("Save");
        int actionDialog = SaveAs.showOpenDialog(this);

        File fileName = new File(SaveAs.getSelectedFile() + ".txt");
        try {
            if (fileName == null) {
                return;
            }
            BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
            outFile.write(n.getText()); //put in textfile

            outFile.close();
        } catch (IOException ex) {
        }

    }

【问题讨论】:

  • 您需要向我们展示您拥有什么以及您尝试了什么。我们不是来为您编写代码的,我们是来帮助调试您所做的工作的。
  • 您的方法 SaveAs 和您的 JFileChooser SaveAs 使用相同的名称,并且不遵循正常的 Java 命名约定,这会造成混淆......
  • 到底是什么问题(又名:你的问题)?

标签: java swing file-io jtextarea


【解决方案1】:

我会使用 JTetArea 自己的 write 方法,因为这样可以轻松写入文件,并且可以很好地处理所有换行符。例如(并借用您的代码):

public class TextEditor extends JFrame {

   int count = 2;
   JTextArea n = new JTextArea();
   final JFileChooser fc = new JFileChooser();

   public void SaveAs() {

      final JFileChooser SaveAs = new JFileChooser();
      SaveAs.setApproveButtonText("Save");
      int actionDialog = SaveAs.showOpenDialog(this);
      if (actionDialog != JFileChooser.APPROVE_OPTION) {
         return;
      }

      File fileName = new File(SaveAs.getSelectedFile() + ".txt");
      BufferedWriter outFile = null;
      try {
         outFile = new BufferedWriter(new FileWriter(fileName));

         n.write(outFile);   // *** here: ***

      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {
         if (outFile != null) {
            try {
               outFile.close();
            } catch (IOException e) {
               // one of the few times that I think that it's OK
               // to leave this blank
            }
         }
      }
   }

}

您的代码中有一些错误。例如这行得通,

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

@SuppressWarnings("serial")
public class TextEditor extends JFrame {

   int count = 2;
   JTextArea textArea = new JTextArea(10, 30);
   final JFileChooser fc = new JFileChooser();

   public TextEditor() {
      add(new JScrollPane(textArea));
      add(new JPanel(){{add(new JButton(new AbstractAction("Save As") {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            saveAs();
         }
      }));}}, BorderLayout.SOUTH);
   }

   public void saveAs() {
      FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("Text File", "txt");
      final JFileChooser saveAsFileChooser = new JFileChooser();
      saveAsFileChooser.setApproveButtonText("Save");
      saveAsFileChooser.setFileFilter(extensionFilter);
      int actionDialog = saveAsFileChooser.showOpenDialog(this);
      if (actionDialog != JFileChooser.APPROVE_OPTION) {
         return;
      }

      // !! File fileName = new File(SaveAs.getSelectedFile() + ".txt");
      File file = saveAsFileChooser.getSelectedFile();
      if (!file.getName().endsWith(".txt")) {
         file = new File(file.getAbsolutePath() + ".txt");
      }

      BufferedWriter outFile = null;
      try {
         outFile = new BufferedWriter(new FileWriter(file));

         textArea.write(outFile);

      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {
         if (outFile != null) {
            try {
               outFile.close();
            } catch (IOException e) {}
         }
      }
   }

   private static void createAndShowGui() {
      TextEditor frame = new TextEditor();

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

【讨论】:

  • 仍然不将文本写入新文件,保存的文件不保存文本
  • @user1267300:“不起作用”并不能告诉我们太多,这将使我们能够告诉您原因。如果您仍然需要我们的帮助,我建议您创建一个sscce(请阅读链接),并向我们展示它是如何不起作用的。
  • n.write(outFile);仍然没有将文本写入新文件
【解决方案2】:

您似乎(尽管您的某些代码丢失了)正在使用FileReader 从所选文件中读取,然后使用FileWriter 写入同一个文件。显然,这是在循环往复。

您需要调用JTextArea 方法(getText() 等)来获取文本,然后将其写入文件。

this.n 是什么?

另请注意,您正在使用 catch (IOException ex) {} 静默捕获异常,即不记录任何错误 - 因此如果出现问题,您将不会获得任何信息。

最后,您应该使用finally 关闭您的文件 - 如果您在try 块中执行此操作,那么如果出现异常,它将不会被关闭。

更新(现在 Q 已被编辑):大概您的 JFileChooser 正在返回一个目录。然后将“.txt”附加到它。我不认为这是你的意思。在写入之前尝试打印出fileName。也请在写之前打印出n.getText(),并告诉我们你看到了什么。还请在 catch 块中添加一个println,以便您确认是否抛出了异常。

【讨论】:

  • 所以现在我有了这个 outFile.write(n.getText()); ('n' 是 jTextArea)但仍然没有将文本写入文件我错过了什么?
  • 不知道,因为我看不到您如何声明和设置n。尝试使用更多代码更新您的问题。您也可以打印出n.getText() 以确认预期的文本确实存在。
【解决方案3】:

你只需要在最后关闭你的文件,它就会将文本写入。

示例:

BufferedWriter wr;
            try { wr = new BufferedWriter(new FileWriter(path));
                wr.write(edytor.getText());
                wr.close();
            } catch (IOException ex) {
                Logger.getLogger(Okno.class.getName()).log(Level.SEVERE, null, ex);
            }

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多