Java 将 jTextArea(即另存为)中的文本保存到新的 .txt 文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9690686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:12:16  来源:igfitidea点击:

Save a the text from a jTextArea (ie Save As) into a new .txt file

javaswingfile-iojtextarea

提问by user1267300

I am busy trying to make a word processor as one of my project and I need the text entered into the jTextArea to be saved as a .txt file with a name and location that the user chooses. note "fc" is the name of i file chooser i have already declared.

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

   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) {
        }

    }

采纳答案by Hovercraft Full Of Eels

I would use the JTetArea's own write method as this will allow easy writing to file and will handle all line feeds nicely. For example (and to borrow your code):

我会使用 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
            }
         }
      }
   }

}

You've got some bugs in your code. For e.g. this works,

您的代码中有一些错误。例如,这有效,

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

}

回答by DNA

You seem (though some of your code is missing) to be reading from the chosen file using FileReaderand then writing to the same file using FileWriter. Clearly, this is going around in circles.

您似乎(尽管您的某些代码丢失了)正在FileReader使用FileWriter. 显然,这是在循环往复。

You need to call JTextAreamethods (getText()etc) to get the text, then write that to the file.

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

What is this.n?

什么是this.n

Also note that you are catching Exceptions silently with catch (IOException ex) {}, i.e. not logging any error - so you won't get any information if something goes wrong.

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

Finally, you should use finallyto close your file - if you do it in the tryblock, it won't get closed if there's an Exception.

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

Update(now that Q has been edited): Presumably your JFileChooser is returning a directory. You are then appending ".txt" to it. I don't think this is what you meant. Try printing out fileNamebefore writing to it. Please also print out n.getText()before writing it, and tell us what you see. Please also put a printlnin teh catch block so you can confirm whether there's an exception thrown.

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

回答by Album

you just need to close your file at the end, so it will write text into.

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

example:

例子:

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