-2

I got many answer regarding this question,but none of them worked in my case. So,my question is consider there is a txt file by the output.txt and i am getting an output on my console as "Hello world My name is mr.cat 127u747rii Hfhdi8a 7hdheui" Now i want the same console output in my output.txt file. Your help will be appreciated. Thanks in advance

Rajat Krishnan
  • 111
  • 2
  • 9
  • This [example](https://stackoverflow.com/questions/12945537/how-to-set-output-stream-to-textarea/12945678#12945678) and this [example](https://stackoverflow.com/questions/22241024/system-out-println-redirection-in-java/22241169#22241169) demonstrate how to capture the "standard out" and redirect it. You just need to supply the end point (ie the file writing) to achieve what you want.*"I got many answer regarding this question,but none of them worked in my case"* You need to explain this further, wha have you actually tried and why didn't it work – MadProgrammer Jan 01 '20 at 21:33

1 Answers1

1

You want to use the FileWriter class, as follows:

File file = new File("/Users/christopherelliott/Desktop/text.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello world My name is mr.cat 127u747rii Hfhdi8a 7hdheui"); // This is the string you want to write
writer.close();

In order to run this code, you will need to have import java.io.*; at the top of your code (this imports the File and FileWriter classes).

If you want to add to the file after you have done writer.close(), you could re-initialize the writer object with the line FileWriter writer = new FileWriter(file, true);. The second parameter there (true) will append to the file instead of write over its past contents. You can read more about this class at https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html.

zpChris
  • 98
  • 1
  • 8
  • And what in case the output of console is to big and keep changes dynamically after every execution? – Rajat Krishnan Jan 01 '20 at 19:49
  • I'm not sure how the size of the output would affect the final answer result? – zpChris Jan 01 '20 at 20:00
  • Can you give an example for what dynamic changes are occurring after every execution? – zpChris Jan 01 '20 at 20:01
  • For example i am using adding two number 10+20 ( user input)and the output is 30 and next time user enters 20+30 now the output is changed to 50,now as per execution flow in 1st execution the txt file should contain result as 30 but after second execution it should be changed to 50,hope you got it what i want to say? – Rajat Krishnan Jan 01 '20 at 20:13
  • Ok, I understand what you mean now, I'll add to my answer; one moment. – zpChris Jan 01 '20 at 20:16
  • I added an extra paragraph that explains how to add to add to the file if you have closed the FileWriter object. – zpChris Jan 01 '20 at 20:23