Java将多行字符串保存到文本文件

发布于 2024-10-21 09:56:10 字数 1038 浏览 4 评论 0原文

我是 Java 新手,试图将多行字符串保存到文本文件中。

现在,它确实可以在我的应用程序中运行。就像,如果我从应用程序中保存文件,然后从应用程序中打开它,它会在行之间放置一个空格。但是,如果我从应用程序保存文件,然后在记事本中打开它,则所有内容都在一行上。

有没有办法让它在所有程序上显示多行?这是我当前的代码:

public static void saveFile(String contents) {

    // Get where the person wants to save the file
    JFileChooser fc = new JFileChooser();

    int rval = fc.showSaveDialog(fc);

        if(rval == JFileChooser.APPROVE_OPTION) {

            File file = fc.getSelectedFile();

            try {
                //File out_file = new File(file);
                BufferedWriter out = new BufferedWriter(new FileWriter(file));
                out.write(contents);
                out.flush();
                out.close();
            } catch(IOException e) {
                messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
            }
        }

        else {
            // Do nothing
            System.out.println("The user choose not to save anything");
        }
}

I am new to Java and trying to save a multi line string to a text file.

Right now, it does work within my application. Like, if I save the file from my application and then open it from my application, it does put a space between lines. However, if I save the file from my app and then open it in Notepad, it is all on one line.

Is there a way to make it show multi line on all programs? Here's my current code:

public static void saveFile(String contents) {

    // Get where the person wants to save the file
    JFileChooser fc = new JFileChooser();

    int rval = fc.showSaveDialog(fc);

        if(rval == JFileChooser.APPROVE_OPTION) {

            File file = fc.getSelectedFile();

            try {
                //File out_file = new File(file);
                BufferedWriter out = new BufferedWriter(new FileWriter(file));
                out.write(contents);
                out.flush();
                out.close();
            } catch(IOException e) {
                messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
            }
        }

        else {
            // Do nothing
            System.out.println("The user choose not to save anything");
        }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

临风闻羌笛 2024-10-28 09:56:10

根据您构建字符串的方式,您可能会遇到行结束问题。记事本不支持unix行结尾(仅\n),它仅支持windows行结尾(\n\r)。尝试使用更强大的编辑器打开保存的文件,和/或确保使用适合您平台的正确行结尾。 java 的系统属性 (System.getProperty("line.separator")) 将为您提供代码运行平台的正确行结尾。

当您构建要保存到文件中的字符串时,您可以附加值,而不是显式指定“\n”或“\n\r”(或在 mac 上为“\r”)作为行结尾该系统属性。

像这样:

String eol = System.getProperty("line.separator");

... somewhere else in your code ...

String texttosave = "Here is a line of text." + eol;

... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);

depending on how you are constructing your string, you may just be running into a line ending problem. Notepad does not support unix line endings (\n only) it only supports windows line endings (\n\r). try opening your saved file using a more robust editor, and/or make sure you are using the proper line endings for your platform. java's system property (System.getProperty("line.separator")) will get you the proper line ending for the platform that the code is running on.

while you're building your string to be saved to the file, rather than explicitly specifying "\n" or "\n\r" (or on the mac "\r") for your line endings, you would instead append the value of that system property.

like so:

String eol = System.getProperty("line.separator");

... somewhere else in your code ...

String texttosave = "Here is a line of text." + eol;

... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);
滥情哥ㄟ 2024-10-28 09:56:10

是的,前面的答案提到了 System.getProperty("line.seperator")。

你的代码没有显示你如何创建字符串内容,但既然你说你是java新手,我想我会提到在java中连接字符串并不好,因为它创建了一个。如果您通过这样做来构建字符串:

String contents = ""
contents = contents + "sometext" + "some more text\n"

那么请考虑使用 java.lang.StrinBuilder

StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();

另一种替代方法是将您计划写入文件的内容流式传输,而不是构建一个大字符串然后输出它。

Yea as the previous answer mentions the System.getProperty("line.seperator").

your code doesn't show how you created String contents but since you said you were new to java I thought i'd mention that in java concatenating Strings is not nice since it creates a. If you are building the String by doing this:

String contents = ""
contents = contents + "sometext" + "some more text\n"

Then consider using java.lang.StrinBuilder instead

StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();

Another alternative is to stream what ever your planning to write to a file rather than building a large string and then outputting that.

酒浓于脸红 2024-10-28 09:56:10

您可以添加类似以下内容:

contents = contents.replaceAll("\\n","\\n\\r");

如果记事本无法正确显示。但是,您可能会遇到不同的问题:在每次保存/加载时,您都会得到多个 \r 字符。然后,为了避免在加载时出现这种情况,您必须调用上面相同的代码,但参数相反。这确实是一个丑陋的解决方案,只是为了让文本在记事本中正确显示。

You could add something like:

contents = contents.replaceAll("\\n","\\n\\r");

if notepad does not display correctly. However you might run into a different problem: at each save/load you will get multiple \r chars. Then to avoid that at load you would have to call the same code above but with reversed parameters. This is really an ugly solution just to get the text to display properly in notepad.

剩一世无双 2024-10-28 09:56:10

我的男朋友也遇到了同样的问题,经过深思熟虑和研究,我什至找到了解决方案。

例如,您可以使用ArrayList来放置TextArea的所有内容,并通过调用save作为参数发送,因为编写器只是写入字符串行,然后我们使用“for”逐行写入最后的ArrayList我们将在 txt 文件中添加 TextArea 内容。
如果有些事情没有意义,我很抱歉谷歌翻译和我不会说英语。

观察Windows记事本,它并不总是跳行,并且全部显示在一行中,使用写字板就可以了。


private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

    String NameFile = Name.getText();
    ArrayList< String > Text = new ArrayList< String >();

    Text.add(TextArea.getText());

    SaveFile(NameFile, Text);
} 

public void SaveFile(String name, ArrayListmessage) {

    path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

    File file1 = new File(path);

    try {

        if (!file1.exists()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

        for (int i = 0; i < message.size(); i++) {

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

        FileReader fr = new FileReader(file1);

        BufferedReader br = new BufferedReader(fr);

        fw = new FileWriter(file1, true);

        bw = new BufferedWriter(fw);

        while (br.ready()) {

            String line = br.readLine();

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error in" + ex);        
}

I had this same problem my guy friend, after much thought and research I even found a solution.

You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.


private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

    String NameFile = Name.getText();
    ArrayList< String > Text = new ArrayList< String >();

    Text.add(TextArea.getText());

    SaveFile(NameFile, Text);
} 

public void SaveFile(String name, ArrayList< String> message) {

    path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

    File file1 = new File(path);

    try {

        if (!file1.exists()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

        for (int i = 0; i < message.size(); i++) {

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

        FileReader fr = new FileReader(file1);

        BufferedReader br = new BufferedReader(fr);

        fw = new FileWriter(file1, true);

        bw = new BufferedWriter(fw);

        while (br.ready()) {

            String line = br.readLine();

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error in" + ex);        
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文