0

For example lets say i have the following String,

String str = "Patient: " + patient +
"\nMonth: " + month +
"\nDay : " + day +
"\nYear: " + year 
+"\nDescription: " + description;

//And I write this data to a file, 
PrintWriter outputFile = new PrintWriter("hello.txt");

outputFile.println(str);

Then the result on the file is just a single line, when I open it, is there a way, to just do the format as the String passed into the file.?

Thank you in advance.

2 Answers2

2

The \n works as expected on UNIX. Using Windows may require \r\n. Please view https://softwareengineering.stackexchange.com/questions/29075/difference-between-n-and-r-n

Community
  • 1
  • 1
J_D
  • 740
  • 8
  • 17
1

It worked for me just as written on a Linux system. If you are using a windows machine, try "\r\n" as new lines instead of just "\n". Also a good habit is to specify the encoding while opening a PrintWriter. Ideally you can use System.getProperty("line.separator") to get the platform dependent line separator.

String lineSeparator = System.getProperty("line.separator");
String str = "Patient: " + "a" +
            lineSeparator + "Month: " + "a" +
            lineSeparator + "Day : " + "a" +
            lineSeparator + "Year: " + "a"
            lineSeparator + "Description: " + "a";

    try {
        PrintWriter outputFile = new PrintWriter("hello.txt", "UTF-8");
        outputFile.println(str);
        outputFile.close();
        System.out.println("writing file");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
FirstName LastName
  • 1,891
  • 5
  • 23
  • 37