Robert
Robert

Reputation: 13

\n not working when printing to txt file

Trying to write a string to a text file, which works, but doesn't include the newline \n part. Can someone tell me why it won't work? \t works fine but this just wont.

FileReader class:

import java.io.*;

public class FileReader
{
    public static void readFile()
    {
        try
        {
            PrintWriter f;
            File file = new File("../webapps/Assignment1/Seats.txt");
            if(!file.exists())
            {
                f = new PrintWriter(file);
                f.write(populateSeats());
                f.close();
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public static String populateSeats()
    {
        String rowID[] = {"A", "B", "C" ,"D" ,"E" ,"F" ,"G" ,"H"};
        String seatPop = "";
        int rowCount = 0;
        int colCount = 1;

        for(int r = 0; r < 8; r++)
        {
            for(int c = 0; c < 8; c++)
            {
                seatPop += "SeatID: " + rowID[rowCount] + colCount + "\n";
                seatPop += "Avail: True \n";
                seatPop += "UserID: null\n";
                seatPop += "Phone: null\n";
                seatPop += "Address: null\n";
                seatPop += "Email: null\n";
                colCount++;
            }
            colCount = 1;
            rowCount++;
        }
        return seatPop;
    }
}

Main class (Just makes an instance of FileReader and then run the method)

FileReader file = new FileReader();

file.readFile();

Upvotes: 0

Views: 267

Answers (2)

SteelToe
SteelToe

Reputation: 2597

When adding a new line for files on windows use \r\n instead of \n.

\n was made specificly for Unix / Linux Systems.

\r\n will add a new line when being used on windows.

So in your code change it to

for (int c = 0; c < 8; c++) {
seatPop += "SeatID: " + rowID[rowCount] + colCount + "\r\n";
// .....
}

However as Tim said in his answer above, the best way would be to use the System.lineSeparator(); method as this will return the proper escape sequence to generate a new line independent of the operating system. As such I would reccomend you use System.lineSeparator(); over \r\n.

Upvotes: -1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

I speculate that the \n are in fact being written to the file, but that the system you are using does not use \n as the line separator. If so, then these characters would be present, be they might be getting rendered as newlines in your editor. Instead, try using a system independent line separator:

System.lineSeparator();     // Java 7 or later; I'll assume this is your case

In your code you might do this:

 for (int c = 0; c < 8; c++) {
    seatPop += "SeatID: " + rowID[rowCount] + colCount + System.lineSeparator();
    // etc.
}

Upvotes: 3

Related Questions