MegaZeroX MegaZeroX - 6 months ago 5x
Java Question

FileWriter won't append new lines

I'm not sure why my output function isn't picking up newlines when it creates a file. Here is the code:

private void outputToFile(){
final JFileChooser fc = new JFileChooser();
fc.setSelectedFile(new File("frequency.txt"));
int returnVal = fc.showSaveDialog(null);
File file = fc.getSelectedFile();
FileWriter writer = new FileWriter(file);
String out = this.toString();
catch(IOException e){
System.out.println("Cancelled and aborted");

My toString method works fine when I print to the command line, but drops all instances of \n in the file output. Here is a sample "broken" output from this function (this is a frequency counter)

Output File:
Q: 5
\n: 7
C: 1
a: 5
t: 6
s: 3
(space): 6
r: 1
e: 4
c: 1
o: 2
l: 3
.: 2
W: 1
,: 1
h: 4
': 1
w: 1
y: 3
\t: 1
R: 1
i: 1
g: 1
?: 1
B: 1
!: 1

There should be new lines after each number there.

If you want the full group of my classes, here they are:


When writing the file, you need to include both a newline and a linefeed character. So, in your toString() method, where you add the "\n" newline, instead add both a linefeed and newline: "\r\n"