How to write console output to a txt file

I tried to write 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"); } 
+62
java file-io console
Jan 03 '09 at 7:48
source share
11 answers

You need to do something like this:

 PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); 

The second statement is key. It changes the value of the supposedly "final" System.out attribute to the provided PrintStream value.

There are similar methods ( setIn and setErr ) for changing standard input and error streams; see javadocs java.lang.System for details.

A more general version of the above:

 PrintStream out = new PrintStream( new FileOutputStream("output.txt", append), autoFlush); System.setOut(out); 

If append is true , the stream will append to the existing file instead of truncating it. If autoflush is true , the output buffer will be flushed when a byte array is written, when one of the println methods is called, or when \n written.




I just wanted to add that it is usually better to use a logging subsystem like Log4j , Logback or standard Java java.util.logging . subsystem. They provide detailed logging control using runtime configuration files, support for scrolling log files, channels in the system log, etc.

Also, if you are not β€œkeeping a journal,” consider the following:

  • With typical shells, you can redirect standard output (or standard error) to a file on the command line; eg,

     $ java MyApp > output.txt 

    See the shell manual or the manual for more information.

  • You can modify your application so that it uses the out stream, passed as a parameter to the method, or through a single injection or dependency injection, instead of writing to System.out .

Changing System.out can cause unpleasant surprises for other code in your JVM that does not expect this to happen. (A properly designed Java library will avoid dependencies on System.out and System.err , but you might not be lucky.)

+117
Jan 03 '09 at 8:04
source share

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

 javac myFile.java java ClassName > a.txt 

The output is saved in a.txt file.

+31
May 9 '13 at 8:16
source share

to save the console output, i.e. write to a file, and also display it on the console, you can use a class, for example:

  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)

+22
Jan 03 '09 at 11:43 on
source share

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 did not include the correct I / O handling in the above class and it does not compile - do it yourself. Also think about setting the file name. Pay attention to the "true" argument. Is recreated every time you call the method)

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

This manual approach is not preferred. Use the registration framework - slf4j, log4j, commons-logging and many others.

+11
Jan 03 '09 at 8:04
source share

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

+7
Jan 03 '09 at 15:33
source share

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

+4
Jan 03 '09 at 8:02
source share

This is my idea of ​​what you are trying to do, and it works great:

 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(); } } 
+3
Jul 19 2018-11-11T00:
source share

The easiest way to write console output to a text file

 //create a file first PrintWriter outputfile = new PrintWriter(filename); //replace your System.out.print("your output"); outputfile.print("your output"); outputfile.close(); 
+2
Apr 09 '16 at 11:39 on
source share

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 a PDF, not a text file, use the dependency below:

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

To create a PDF file, 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(); } } 
0
Jun 01. '16 at 22:43
source share
 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 the absolute path for FileWriter. It works for me like a charm. Also make sure the file is present at this location. Else It will throw a FileNotFoundException. This method does not create a new file at the destination location if the file is not found.

0
Mar 15 '17 at 8:33
source share

In netbeans, you can right-click and then save as a .txt file. Then, based on the generated .txt file, you can convert it to any format you want to receive.

-one
Sep 25 '17 at 6:24
source share



All Articles