How to write console output to a txt file
You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out
attribute to be the supplied PrintStream value.
There are analogous methods (setIn
and setErr
) for changing the standard input and error streams; refer to the java.lang.System
javadocs for details.
A more general version of the above is this:
PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
If append
is true
, the stream will append to an existing file instead of truncating it. If autoflush
is true
, the output buffer will be flushed whenever a byte array is written, one of the println
methods is called, or a \n
is written.
I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
Alternatively, if you are not "logging" then consider the following:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
$ java MyApp > output.txt
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an
out
stream passed as a method parameter or via a singleton or dependency injection rather than writing toSystem.out
.
Changing System.out
may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out
and System.err
, but you could be unlucky.)
Print console output to text file
If you want to save all the print statements into a text file then, you can copy the things you want to save in the file and store them in a variable and then write them in the text file. For example, I edited your code to this:
import time
import sys
# variable declaration
user_cave = 0
cave = 0
result = ""
playagain = "Y"
while playagain == "Y" or playagain == "y":
f = open("Dragon Game.txt", 'w')
f.write("")
print(
"\nYou are in the Kingdom of Dragons.\nIn front of you, you see two caves.\nIn one cave, the dragon is friendly and will share his treasure with you.\nThe other dragon is hungry and will eat you on sight!\nGood luck on your journey\n")
while True: # including while true because program should till break
try: # repeat till user give correct value
user_cave = int(input("Please select cave 1,2,3,4 or 5 : "))
if user_cave > 0 and user_cave < 6:
break
else:
continue
except:
""
# create random number to differentiate
cave = random.randrange(1, 3)
# Bad dragon
if cave == 1:
result = "Gobbles you down!"
# Good Dragon
elif cave == 2:
result = "Greets you before share his treasure!"
txt = f"\nYou are in the Kingdom of Dragons.\nIn front of you, you see two caves.\nIn one cave, the dragon is friendly and will share his treasure with you.\nThe other dragon is hungry and will eat you on sight!\nGood luck on your journey\nYou approach the cave....{str(user_cave)}\nA large dragon jumps out in front of you!\nHE OPENS HIS JAWS AND.....\n{result}"
f = open("Dragon Game.txt", "a")
f.write(txt)
print("\nYou approach the cave.... " + str(user_cave))
time.sleep(1.5)
print("A large dragon jumps out in front of you!")
time.sleep(1.5)
print("HE OPENS HIS JAWS AND.....\n")
time.sleep(2)
print(result, "\n")
playagain = input("Do you want to play again ? [y/n] : ")
Just, before running this file, you have to create a file named Dragon Game.txt
It's compulsory to run the code.
Java: How to save console output to a text file?
System class provide you a way to dump output in different stream which is System#setOut(PrintStream out)
Using this method you can pass you FileInputstream to System.setOut
and you can save the console output.
PrintStream printStream = new PrintStream(new FileOutputStream(file));
System.setOut(printStream);
One interesting part of this question is though out
is declared as final in System class but still you reassign this by System#setOut
.
Related Topics
Date Object Simpledateformat Not Parsing Timestamp String Correctly in Java (Android) Environment
Android Changing Floating Action Button Color
Android - Setting a Timeout for an Asynctask
How to Get a Context in a Recycler View Adapter
Opengl Es2 Alpha Test Problems
Gradle - What Is a Non-Zero Exit Value and How to Fix It
Android: How to Stretch an Image to the Screen Width While Maintaining Aspect Ratio
How to Make a Copy of a File in Android
Transitive Dependencies Not Resolved for Aar Library Using Gradle
What Is the Jasperrepots-Fonts Jar for and How to Use It
How to View Visual Gc in Visualvm
Getting Java.Net.Sockettimeoutexception: Connection Timed Out in Android
Picking a Random Element from a Set
How to Create a Bks (Bouncycastle) Format Java Keystore That Contains a Client Certificate Chain