69

I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What's wrong?

try {
      //create a buffered reader that connects to the console, we use it so we can read lines
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

      //read a line from the console
      String lineFromInput = in.readLine();

      //create an print writer for writing to a file
      PrintWriter out = new PrintWriter(new FileWriter("output.txt"));

      //output to the file a line
      out.println(lineFromInput);

      //close the file (VERY IMPORTANT!)
      out.close();
   }
      catch(IOException e1) {
        System.out.println("Error during reading/writing");
   }
Dropout
  • 13,653
  • 10
  • 56
  • 109
Jessy
  • 15,321
  • 31
  • 83
  • 100
  • 1
    The code sample you gave writes the console *input* to a file. It's not very clear what you are trying to achieve. Can you give more details? – daphshez Jan 03 '10 at 07:53
  • I have many output on the console which resulted from system.out.println. I'm trying to write all these output to a .txt file. – Jessy Jan 03 '10 at 07:57

11 Answers11

132

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 to System.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.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
37

There is no need to write any code, just in cmd on the console you can write:

javac myFile.java
java ClassName > a.txt

The output data is stored in the a.txt file.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
ali ahmad
  • 371
  • 3
  • 2
  • 10
    This works for the standard output. If you want capture also the error output use: "java ClassName > a.txt 2>&1". For example the simple "java -version" writes to the console.err which you only can capture with my extension. – Heri Dec 23 '14 at 15:51
  • 2
    for jar file ```java -jar yourapp.jar > a.txt 2>&1``` – user9268852 Jun 03 '19 at 14:19
27

to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:

    public class TeePrintStream extends PrintStream {
        private final PrintStream second;

        public TeePrintStream(OutputStream main, PrintStream second) {
            super(main);
            this.second = second;
        }

        /**
         * Closes the main stream. 
         * The second stream is just flushed but <b>not</b> closed.
         * @see java.io.PrintStream#close()
         */
        @Override
        public void close() {
            // just for documentation
            super.close();
        }

        @Override
        public void flush() {
            super.flush();
            second.flush();
        }

        @Override
        public void write(byte[] buf, int off, int len) {
            super.write(buf, off, len);
            second.write(buf, off, len);
        }

        @Override
        public void write(int b) {
            super.write(b);
            second.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            super.write(b);
            second.write(b);
        }
    }

and used as in:

    FileOutputStream file = new FileOutputStream("test.txt");
    TeePrintStream tee = new TeePrintStream(file, System.out);
    System.setOut(tee);

(just an idea, not complete)

user85421
  • 28,957
  • 10
  • 64
  • 87
12

Create the following method:

public class Logger {
    public static void log(String message) { 
      PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
      out.write(message);
      out.close();
    }
}

(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)

Then instead of System.out.println(str) call Logger.log(str)

This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
7

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    Sorry, i missed the ampersand in the command. The command in unix is: "java -jar yourApplication.jar >& yourLogFile.txt" – drzymala Feb 02 '13 at 01:39
4

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

ZoogieZork
  • 11,215
  • 5
  • 45
  • 42
3

This is my idea of what you are trying to do and it works fine:

public static void main(String[] args) throws IOException{

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
    try {
        String inputLine = null;
        do {
            inputLine=in.readLine();
            out.write(inputLine);
            out.newLine();
        } while (!inputLine.equalsIgnoreCase("eof"));
        System.out.print("Write Successful");
    } catch(IOException e1) {
        System.out.println("Error during reading/writing");
    } finally {
        out.close();
        in.close();
    }
}
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Abhiyank
  • 31
  • 1
1

The easiest way to write console output to text file is

//create a file first    
    PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
    outputfile.print("your output");
    outputfile.close(); 
Prakash Kandel
  • 1,043
  • 6
  • 12
  • 3
    Please don't make edits like [this](http://stackoverflow.com/review/suggested-edits/12501763) anymore. You actively made it worse - for no clear reason. Please don't abuse edits to gain reputation. – Rob May 28 '16 at 04:30
0

To write console output to a txt file

public static void main(String[] args) {
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 100; i++) {
        String str = null;
        str = +i + ":-  HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
        ls.add(str);
    }
    String listString = "";
    for (String s : ls) {
        listString += s + "\n";
    }
    FileWriter writer = null;
    try {
        writer = new FileWriter("final.txt");
        writer.write(listString);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

If you want to generate the PDF rather then the text file, you use the dependency given below:

<dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.0.6</version>
</dependency>

To generate a PDF, use this code:

public static void main(String[] args) {
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 100; i++) {
        String str = null;
        str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
        ls.add(str);
    }
    String listString = "";

    for (String s : ls) {
        listString += s + "\n";
    }
    Document document = new Document();
    try {
        PdfWriter writer1 = PdfWriter
                .getInstance(
                        document,
                        new FileOutputStream(
                                "final_pdf.pdf"));
        document.open();
        document.add(new Paragraph(listString));
        document.close();
        writer1.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}
  • 1
    I don't think readers need all that code setting up a list of strings to write; they could do that themselves. This answer boils down to "after you write something to System.out, also write it to a file with a FileWriter or a PdfWriter". – Noumenon Jun 01 '16 at 23:09
  • @Noumenon; Sir it may be possible that you have lot of knowledge of java but on this open forum there is lot of fresher and new comers and complete piece of code is a great help for them. – Ashish Vishnoi Jun 01 '16 at 23:36
  • Thanks for the mature response. You're right that it helps to have something you can actually run and test -- I provide working examples too. I just don't want to have to read through the whole example to find the answer. This same answer would be improved if preceded by a summary: "Just write it to a file with a FileWriter. Working example:" As a side note, Stack Overflow is different from an open forum in that answers are meant to help many future readers besides the original poster. They're more likely to try out and upvote an approach that's easy to understand at a glance. – Noumenon Jun 01 '16 at 23:52
0
PrintWriter out = null;
try {
    out = new PrintWriter(new FileWriter("C:\\testing.txt"));
    } catch (IOException e) {
            e.printStackTrace();
    }
out.println("output");
out.close();

I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.

-1

In netbeans, you can right click the mouse and then save as a .txt file. Then, based on the created .txt file, you can convert to the file in any format you want to get.

htlbydgod
  • 330
  • 2
  • 8