[java] How to write console output to a txt file

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");
   }

This question is related to java file-io console

The answer is


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.


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.


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();
    }
}

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


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(); 

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)


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


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.


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.


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();
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working