简体   繁体   English

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

[英]Java save multiline string to text file

I am new to Java and trying to save a multi line string to a text file. 我是Java的新手,正在尝试将多行字符串保存到文本文件中。

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

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). 记事本不支持UNIX行尾(仅\\ n),仅支持Windows行尾(\\ 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. java的系统属性(System.getProperty(“ line.separator”))将为您提供运行代码的平台的正确行尾。

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. 在构建要保存到文件中的字符串时,而不是为行尾显式指定“ \\ n”或“ \\ n \\ r”(或在Mac的“ \\ r”上),您可以附加该值该系统属性。

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

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. 您可以使用ArrayList来放置TextArea的所有内容作为示例,并通过调用save来作为参数发送,因为编写者刚刚编写了字符串行,然后我们使用“ for”一行一行地最后编写我们的ArrayList我们将在txt文件中使用TextArea内容。 if something does not make sense, I'm sorry is google translator and I who do not speak English. 如果没有什么意义,对不起,我是google翻译者,我不会说英语。

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok. 观看Windows记事本,它并不总是跳行,而是全部显示在一行中,请使用写字板确定。


private void SaveActionPerformed(java.awt.event.ActionEvent evt) { 私人无效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) { 公共无效SaveFile(字符串名称,ArrayList <String>消息){

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

Yea as the previous answer mentions the System.getProperty("line.seperator"). 是的,前面的答案提到了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. 您的代码未显示如何创建String内容,但是由于您说过您是Java的新手,所以我想我提到在Java中串联Strings不好,因为它创建了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 然后考虑改用java.lang.StrinBuilder

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. 另一种选择是流式传输您打算写入文件的内容,而不是构建一个大字符串然后输出。

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. 但是,您可能会遇到一个不同的问题:在每次保存/加载时,您将获得多个\\ r字符。 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. 仅使文本正确显示在记事本中,这确实是一个丑陋的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM