Sorry for the vague title. What I have is a program which basically takes user input then prints it to a file. Pretty simple. The input consists of a memo title and a subsequent memo to be filed under that title. Between the two there will be a date stamp.
The code I have for printing the file looks like this:
System.out.println("Memo topic (enter -1 to end):");
String message = console.nextLine();
now = new Date();
String dateStamp = now.toString();
out.println(topic + "\n" + dateStamp + "\n" + message);
out is the name of a PrintWriter I create earlier in the program. The console displays the instructions and takes the input then write them to a file. When I read the text in the file it all runs together and looks like this:
ThanksgivingWed Nov 4 14:39:36 CST"Pick up some turkey at the Kroger, you
lazy bum!" said Mom.
However, if I change the output to just print to the console, the line break characters actually work and the three pieces of the output string are divided by line. How do I modify this to work correctly as output to a file?
I'm assuming you're testing this on Windows. That would cause a problem, because on Windows, new lines are represented by \r\n
(carriage return, line feed), and not all applications will happily accept just the \n
.
In order to get a system-agnostic line separator, you should use System.lineSeparator()
instead, which
Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator.
On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
So your code would become this:
out.println(topic + System.lineSeparator() + dateStamp + System.lineSeparator() + message);