2

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

4 Answers 4

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

wordpad would be a "more robust editor" in this situation. You can also use a program like unix2dos to change the line endings over so notepad will recognize them.
Okay. I don't really know how to apply that though. How could I make it use the right line seperator?
Notepad++ is my editor of choice for a stripped down, uninvasive code/data editor.
0

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.

1 Comment

I'm getting the String from a text area. I'm making a program sort of like Notepad.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.