【问题标题】:How to fix the New Line when saving file in a document taking text from a JTextArea如何在从 JTextArea 获取文本的文档中保存文件时修复新行
【发布时间】:2015-11-24 14:25:48
【问题描述】:
import java.awt.BorderLayout;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Formatter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class FileDemonstrationJFileChooser extends JFrame {
    private JTextArea outputArea;
    private JScrollPane scrollPane;
    JFileChooser fileChooser = new JFileChooser();

    public FileDemonstrationJFileChooser() {
        // TODO Auto-generated constructor stub
        super("Testing class file");
        outputArea = new JTextArea();
        scrollPane = new JScrollPane(outputArea);
        add(scrollPane, BorderLayout.CENTER);
        setSize(400, 400);
        setVisible(true);

        analyzePath();

        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            // save to file
            String toSave = outputArea.getText();
            try {
                Formatter writer = new Formatter( new File(file+".txt"));
                writer.format(toSave); //Problems here occurs
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            JOptionPane.showMessageDialog(this,
                    "Message saved.(" + file.getName() + ")", "File Saved",
                    JOptionPane.INFORMATION_MESSAGE);

        }
    }

    private File getFileOrDirectory() {

        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.CANCEL_OPTION) {
            System.exit(1);
        }
        File fileName = fileChooser.getSelectedFile();
        if ((fileName == null) || (fileName.getName().equals(""))) {
            JOptionPane.showMessageDialog(this, "Invalid name", "Invalid name",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        return fileName;
    }

    private void analyzePath() {
        File name = getFileOrDirectory();
        if (name.exists()) {
            outputArea.setText(String.format(
                    "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", name
                            .getName(), " exists", (name.isFile() ? "is a file"
                            : "is not a file"),
                    (name.isDirectory() ? "is a directory"
                            : "is not a directory"),
                    (name.isAbsolute() ? "is absolute path"
                            : "is not absolute path"), "Last modified: ", name
                            .lastModified(), "Length: ", name.length(),
                    "Path: ", name.getPath(), "Absolute path: ", name
                            .getAbsolutePath(), "Parent: ", name.getParent()));

            if (name.isDirectory()) {
                String[] directory = name.list();
                outputArea.append("\n\nDirectory contents:\n");

                for (String directoryName : directory) {
                    outputArea.append(directoryName + "\n");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, name + " does not exist.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }

    }
}

我的代码用于写入带有JFileChooser 的文件并将其保存在硬盘中。但是在将其写入文件时会出现问题,它不会占用新行。它将整个文本区域的文本保存在一行中。怎么解决??

当我保存文件时,它只将其内容保存在一行中,不像JTextArea 中那样。也就是说,新行不出现。它将所有内容保存在一行中。那么我该如何解决呢??

【问题讨论】:

标签: java swing newline jtextarea jfilechooser


【解决方案1】:

Document 只会存储“\n”来表示换行符。根据您使用的文本组件,getText() 方法会将“\n”替换为适合您平台的换行符字符串 (JTextPane) 或在文本中保留“\n” (JTextArea)。查看Text and New Lines 了解更多信息。

不要使用格式化程序来编写文本。格式化程序不知道文本的来源。

而只是使用JTextArea提供的write()方法:

FileWriter writer = new FileWriter( new File(...) );
BufferedWriter bw = new BufferedWriter( writer );
textArea.write( bw );
bw.close();

write() 方法知道如何处理行尾字符串。

【讨论】:

    【解决方案2】:

    不要使用\n,而是使用自Java 7 起可用的System.getProperty("line.separator")System#lineSeparator,以获得取决于平台(Windows、*nix)的适当行分隔符。

    【讨论】:

    • 我不会从硬编码字符串中获取文本,我将在其中给出新行。我正在从 JTextArea 中获取文本。那么,当 JTextArea 中出现新行时,如何在文件中添加一个新行来保存此文本。这意味着我想保存文本区域中的所有文本并将其保存到类似于 textArea 的文本格式的文件中。
    【解决方案3】:

    "\n" 适用于控制台输出,但不适用于文件。 使用"\r\n"(适用于Windows)然后保存它应该可以解决问题。

    【讨论】:

    • 文件中的行分隔符取决于操作系统。这与使用\n\r\n 无关。
    【解决方案4】:

    可以轻松插入换行符\r\n 是windows 回车。所以这只适用于windows。您可以检查您正在运行的操作系统,而不是硬编码每个操作系统(如 windows、linux 等)的回车符......

    但请坚持另一种更简单的方法。只需将System.getProperty("line.separator") 附加到您要写入文件的字符串中,它就会自动为您的操作系统附加回车符。

    希望有帮助!

    【讨论】:

    • 我不会从硬编码字符串中获取文本,我将在其中给出新行。我正在从 JTextArea 中获取文本。那么,当 JTextArea 中出现新行时,如何在文件中添加一个新行来保存此文本。这意味着我想保存文本区域中的所有文本并将其保存到类似于 textArea 的文本格式的文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多