簡體   English   中英

將文本從jTextArea保存(即另存為)到新的.txt文件中

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

我正忙於將文字處理程序作為我的項目之一,我需要將輸入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) {
        }

    }

我將使用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();
         }
      });
   }

}

您似乎(盡管有些代碼丟失了)正在使用FileReader從所選文件中讀取,然后使用FileWriter寫入同一文件。 顯然,這是繞圈子的。

您需要調用JTextArea方法( getText()等)以獲取文本,然后將其寫入文件。

這是this.n

另請注意,您正在使用catch (IOException ex) {}靜默捕獲異常,即不記錄任何錯誤-因此,如果出現問題,您將不會獲得任何信息。

最后,您應該使用finally來關閉文件-如果在try塊中進行操作,則在出現異常的情況下它不會被關閉。

更新 (現在Q已被編輯):大概您的JFileChooser正在返回目錄。 然后,您將附加“ .txt”。 我認為這不是您的意思。 嘗試在寫入fileName之前將其打印出來。 還要在編寫之前打印出n.getText() ,然后告訴我們您所看到的內容。 請同時將一個println放入catch塊中,以便您確認是否引發了異常。

您只需要在最后關閉文件,即可將文本寫入其中。

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM