Reputation: 67
I want to save all the text on the terminal as a output on a text file. For the output there can be a function to be used instead of System.out.println()
class OutSave
{
String output;
public static void main()
{
output="";
print("Print this");
print("And save this");
}
public static print(String p)
{
output=output+"\n"+p;
System.out.println(p);
}
}
Something like this but I cannot figure this out for the inputs supplied by the user.
Thanks in Advance
Upvotes: 1
Views: 2511
Reputation: 500
Here is a simple example of how to write a log file of what you are printing.
class OutSave
{
File output = new File("output.txt");
public static void main()
{
print("Print this");
print("And save this");
}
public static print(String str)
{
System.out.println(str);
writeToFile(output, str);
}
public void writeToFile(File file, String str) {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(str);
bw.close();
}
}
Edit: Log user input (ints)
Boolean running = true;
System.out.println("Enter a Number: ");
while (true) {
while (!sc.hasNextInt()) {
System.out.println("Try again, Enter a Number: "); //invalid entry
sc.nextLine();
}
WriteToFile(output, Integer.toString(sc.nextInt()));
}
You could call this code from a method then change the running boolean to exit the loop when you are done as this will hang your program in the input loop if you do not exit. Might be a good idea to thread this too.
Upvotes: 1
Reputation: 6363
The usual way of doing this doesn't require doing anything inside your Java program, and works for any program, regardless of the language it was originally written in.
From a command line, in most shells (bash, C shell, MS-DOS, etc.), run:
$program > outfile.txt
Where $program
is the name of the executable.
This is commonly known as redirection.
Upvotes: 1
Reputation: 11
you can use File writer check the link : http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html
Upvotes: 0