I can print line by line using toString to the console, but how come it doesn’t do the same when I put it in a textfile?
public class NewClass
{
@Override
public String toString()
{
return ("John " + "\n" + "jumps " + "\n" + "fences");
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Sandbox
{
public static void main(String[] args) throws IOException
{
NewClass object = new NewClass();
FileWriter file = new FileWriter("output.txt");
PrintWriter output = new PrintWriter(file);
output.println(object.toString());
output.close();
System.out.println(object.toString());
}
}
CONSOLE OUTPUT:
John
jumps
fences
output.txt
John jumps fences
Since you are on Windows, instead of
\nuse\r\n(carriage return + line feed).Or better yet, use
System.getProperty("line.separator")to obtain the sequence used by operating system to separate lines in text files.