How to Read From the Console in Java

coffee.lang.System out and err objects are used to write text data to the standard output stream and standard error stream. The default output stream is control-line console. But System class also provides a method for you to redirect the standard output stream to other destinations such as file stream. With this, you can log text information to a log file in your coffee program.

i. Redirect Java Organisation Output Stream Methods.

java.lang.System grade provides the beneath methods to gear up standard output stream to custom stream.

  1. setOut(PrintStream ps): Gear up standard information output to a specified print stream such every bit a file stream.
  2. setErr(PrintStream ps):  Fix standard fault output to a specified print stream such as a file stream.
  3. setIn(InputStream is): Set standard input stream to a custom input stream.

2. Redirect Java Out Error Stream Examples.

Beneath are the steps of redirect output stream to file stream.

  1. Create a file output impress stream.
    PrintStream fileOut = new PrintStream("./out.txt");
  2. Call System.setOut method to set above PrintStream equally the new standard output stream.
    Organisation.setOut(fileOut);
  3. Phone call System.out.println to write text data to the file.
    Organization.out.println("Email " + line + " is valid. Please input another one.");

3. Write Panel Output To Text File In Coffee Examples.

Beneath is the total example source lawmaking.

package com.dev2qa.java.basic;  import java.io.FileNotFoundException; import coffee.io.PrintStream; import java.util.Scanner;  public course OutputStreamRedirect {      public static void principal(String[] args) {          endeavor         {             // Save original out stream.             PrintStream originalOut = System.out;             // Salve original err stream.             PrintStream originalErr = System.err;              // Create a new file output stream.             PrintStream fileOut = new PrintStream("./out.txt");             // Create a new file error stream.              PrintStream fileErr = new PrintStream("./err.txt");              // Redirect standard out to file.             System.setOut(fileOut);             // Redirect standard err to file.             System.setErr(fileErr);              // Wrapped Scanner to get user input.             Scanner scanner = new Scanner(System.in);              // Print data in command panel.             originalOut.println("Delight input your e-mail. ");              // Read string line.             String line = scanner.nextLine();              while(truthful)             {                 // If user input 'quit' then suspension the loop.                 if("quit".equalsIgnoreCase(line))                 {                     intermission;                 }                  if(!isValidEmail(line))                 {                     // If user input is not a valid email then write log data to ./err.txt file and console.                     originalErr.println("Email " + line + " is non a valid email. Please input over again.");                     System.err.println("Email " + line + " is not a valid electronic mail. ");                 }else                 {                     // If user input a valid e-mail and then write the email to ./out.txt and console.                     originalOut.println("Electronic mail " + line + " is valid. Delight input another one.");                     System.out.println("Email " + line + " is valid. Please input another 1.");                 }                 // Become next user input line text.                 line = scanner.nextLine();             }              originalOut.println("Program go out. ");             System.out.println("Program exit. ");              // Do not forget ready original output and mistake stream back again.             System.setOut(originalOut);             Arrangement.setErr(originalErr);          }catch(FileNotFoundException ex)         {             ex.printStackTrace();         }     }      /* Check whether the string is an email address or non. */     individual static boolean isValidEmail(String email)     {         boolean ret = true;          if(electronic mail==nil || email.trim().length()==0)         {             ret = false;         }else         {             int index = email.indexOf("@");             if(index == -i)             {                 ret = false;             }         }          return ret;     }  }

Later executing the higher up code, you can see two files out.txt and err.txt are generated under the electric current java form execution folder equally below.

redirect-standard-output-error-stream-to-file-stream-example

Beneath is another method to write user input in control line panel to text file in java.

package com.dev2qa.java.basic;  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter;  public class OutputStreamRedirect {      public static void main(String[] args) {                           try {                            // Create an instance of InputStreamReader class, information technology is used to read user input from command line panel.               InputStreamReader isr = new InputStreamReader(System.in);                              // Create an instance of OutputStreamWriter grade, it is used to write text to control line console.               OutputStreamWriter osw = new OutputStreamWriter(System.out);                                             // Create a BufferedReader object and employ this object to connect to the organization.in(command line console) to get user input text.               BufferedReader br = new BufferedReader(isr);                              // Create a BufferedWriter object to write text to system.out.               BufferedWriter bw = new BufferedWriter(osw);                              bw.write("Please input a valid email address.\r\north");               bw.affluent();                // Get user input text line from the command line console.               String line = br.readLine();                if(isValidEmail(line))               {             	  // If user input valid email accost.             	  String text = line + " is a valid email accost.\r\northward";             	               	  // Print the text to system.out command line console.             	  bw.write(text);             	  bw.flush();                                	  // Print the user input email address to a text file.                   FileWriter fw = new FileWriter("out.txt");                   PrintWriter pw = new PrintWriter(fw);                   pw.println(text);                   // Practice not forget close the to a higher place writers to shut the file pointer.                   pw.close();               }else {             	               	  // If user input invalid email address.               	  String text = line + " is not a valid email address.\r\n";             	               	  // Print the error text to system.out command line console.             	  bw.write(text);             	  bw.flush();             	               	  // Print the error text to an err.txt file.             	  FileWriter fw = new FileWriter("err.txt");                   PrintWriter prisoner of war = new PrintWriter(fw);                   pw.println(text);                   // Close the above writer object to shut the file.                   pw.shut();               }            }grab(IOException e1) {                 Arrangement.out.println("Error during reading/writing");            }     }                             /* Check whether the string is an email address or not. */     private static boolean isValidEmail(String email)     {         boolean ret = truthful;                  if(email==zero || email.trim().length()==0)         {             ret = false;         }else         {             int index = e-mail.indexOf("@");             if(index == -1)             {                 ret = false;             }         }                  return ret;     }  }          

newmancusid1996.blogspot.com

Source: https://www.dev2qa.com/how-to-write-console-output-to-text-file-in-java/

0 Response to "How to Read From the Console in Java"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel