How to copy the terminal output (and input) to a file in java

2.3k views Asked by At

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

3

There are 3 answers

4
Daedric On BEST ANSWER

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.

2
Krim_0 On

you can use File writer check the link : http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html

2
Paul Brinkley On

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.