简体   繁体   中英

String to file not maintaing line breaks displays in terminal correclty java

I want to read a text file , change some text then output to a text file. I'd open this file in notepad

New to Java - This has been rehashed and posted in different way throughout the forum. They always seem to say your missing the /n in the string - I thought I did this in the below code.

The part that is confusing to me is it displays in my terminal correctly when I use the showfile method.

I assume its the way I'm writing the file. I'd like to continue to use my method instead of the String variable

Original file contains text

Bob

Red

Door

I use this to read the text file and input it in a string.

public void readFile(String fileName)
{
    fileText = "";

    try
    {
        Scanner file = new Scanner(new File(fileName));
        while (file.hasNextLine())
        {
            String line = file.nextLine();
            fileText += line +"\n";
        }
        file.close();
    }
    catch (Exception e)
    {
         System.out.println(e);

   }

I use a method to swap all "R"s to "B"s.

I use showFile method and it displays in my terminal correctly

This shows correctly

Bob

Bed

Door

public String showFile()
{
    return fileText;
}

But then I try output the string to a file using.

try {
        File file = new File("test1.txt");
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(startupModified.showFile());
        fileWriter.flush();
        fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

It keeps my spacing but I loose my line breaks

Displays:

Bob Bed Door

This is the constructor class for startupModified

 public StartUpFile(String fileName)
{
    readFile(fileName);
        }

functions correctly now

changed fileText += line +"\\n";

to fileText += line +"\\r\\n";

I assumed it was the writer because it displayed correctly in the terminal.

Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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