How to write console output to a txt file

JavaFile IoConsole

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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)

Solution 4 - Java

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, http://logging.apache.org/log4j/1.2/index.html">log4j</a>;, http://commons.apache.org/logging/">commons-logging</a>;, and many more

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJessyView Question on Stackoverflow
Solution 1 - JavaStephen CView Answer on Stackoverflow
Solution 2 - Javaali ahmadView Answer on Stackoverflow
Solution 3 - Javauser85421View Answer on Stackoverflow
Solution 4 - JavaBozhoView Answer on Stackoverflow
Solution 5 - JavatrashgodView Answer on Stackoverflow
Solution 6 - JavaZoogieZorkView Answer on Stackoverflow
Solution 7 - JavaAbhiyankView Answer on Stackoverflow
Solution 8 - JavaPrakash KandelView Answer on Stackoverflow
Solution 9 - JavaAshish VishnoiView Answer on Stackoverflow
Solution 10 - Javadhayanand baskarView Answer on Stackoverflow
Solution 11 - JavahtlbydgodView Answer on Stackoverflow