After running my program I get this beautifully formatted text:
What do I need add to my code in order to get this text outputted to a .txt file exactly as is?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assuming you’re currently writing your output to the screen using something like
System.out.Println(...), a comparable way to write text to a file is to use a PrintStream.You should be able to find many examples of how to do that if you search; here’s one.
ps. one caution: the “beautifully formatted” part of your text probably relies on the output being displayed in a monospaced font (all characters the same width); if viewed in a non-monospaced font, the columns won’t line up. If you’re saving it as a plain .txt file, you don’t have control over what font someone else will use to display that file when they open it.
Update:
There are a couple of approaches you could take, if you find you’ve got a program full of
System.out.printlncalls and you want to direct the output to a file instead.1) The quick & dirty way would be to open a PrintStream to your desired output file, then call
System.setOut()to redirectSystem.outto the specified PrintStream.2) A perhaps cleaner way would be to rewrite all the calls of
System.out.printlnto use your own output method. That way when you want to change how you’re handling output (for example, send it to multiple files, to both the screen and a file, or whatever), you have just one place to change. More work up front, but gives you more flexibility in the end.