Summary of several methods for Java reading data from the console _java

Source: Internet
Author: User
Tags readline

There are several ways to read the information from the console in Java, and then check it out!

(1) JDK 1.4 (JDK 1.5 and JDK 1.6 are also compatible with this method)

public class TestConsole1 {public
  static void Main (string[] args) {
    String str = readdatafromconsole (' Please Inpu T string:);
    SYSTEM.OUT.PRINTLN ("The information from console: + str");
  }

  /**
   * Use InputStreamReader and system.in to read data from console
   * * 
   @param prompt
   * *      
   @return I Nput string
   *
  /private static string Readdatafromconsole (String prompt) {
    BufferedReader br = new BufferedReader (New InputStreamReader (system.in));
    String str = null;
    try {
      System.out.print (prompt);
      str = Br.readline ();

    } catch (IOException e) {
      e.printstacktrace ();
    }
    return str;
  }
}

(2) JDK 1.5 (read with scanner)

public class TestConsole2 {public
  static void Main (string[] args) {
    String str = readdatafromconsole (' Please Inpu T string: ");
    SYSTEM.OUT.PRINTLN ("The Information from console:" + str);
  }

  /**
   * Use Java.util.Scanner to read data from console
   * * 
   @param prompt * * 
   @return Input string
   
    */
  private static string Readdatafromconsole (String prompt) {
    Scanner Scanner = new Scanner (system.in);
    System.out.print (prompt);
    return Scanner.nextline ();
  }

   

Scanner can also easily scan the files, read the information inside and convert to the type you want, such as the "2 2.2 3.3 3.33 4.5 done" sum, see the following code:

public class TestConsole4 {public static void main (string[] args) throws IOException {FileWriter fw = new FILEWR
    ITER ("Num.txt");
    Fw.write ("2 2.2 3.3 3.33 4.5 done");

    Fw.close ();
  System.out.println ("The Sum is" +scanfileforsum ("Num.txt"));
    public static double Scanfileforsum (String fileName) throws IOException {double sum = 0.0;
    FileReader FR = null;
      try {fr = new FileReader (fileName);
      
      Scanner Scanner = new Scanner (FR);

        while (Scanner.hasnext ()) {if (scanner.hasnextdouble ()) {sum = sum + scanner.nextdouble ();

          else {String str = scanner.next ();
          if (Str.equals ("Done")) {break;
          else {throw new RuntimeException ("File Format is wrong!"); catch (FileNotFoundException e) {throw new RuntimeException ("File" + FileName + "not Found! ");}
    finally {if (FR!= null) fr.close ();return sum; }
}

(3) JDK 1.6 (read with java.io.Console)

JDK6 provides a java.io.Console class for accessing character-based console devices.

If you want to interact with terminal under Windows CMD or Linux, you can do it with the console class. (Similar to system.in and System.out)

But we don't always get the console available, and whether a JVM has the available console depends on how the underlying platform and JVM are invoked.

If the JVM is started in an interactive command line (such as Windows cmd), and the input output is not redirected to another location, an available console instance can be obtained.

In the case of the IDE, the console instance cannot be obtained because, in the IDE's environment, the standard input and output streams are redirected and the input output from the system console is redirected to the IDE's console

public class TestConsole3 {public
  static void Main (string[] args) {
    String str = readdatafromconsole (' Please Inpu T string: ");
    SYSTEM.OUT.PRINTLN ("The Information from console:" + str);
  }

  /**
   * Use Java.io.console to read data from console
   * * 
   @param prompt * * 
   @return Input String
   * /
  private static string Readdatafromconsole (String prompt) {
    console console = System.Console ();
    if (console = = null) {
      throw new IllegalStateException ("console is not available!");
    }
    return Console.ReadLine (prompt);
  }

Another feature of the console class is that it deals specifically with security characters such as passwords (input without echo). Specifically provided Readpassword () method, the specific application see the following code:

public class TestConsole5 {public
  
   static void Main (string[] args) {
      console console = System.Console ();
      if (console = = null) {
        throw new IllegalStateException ("console is not available!");
      }
      
      while (true) {
      String username = console.readline ("username:");
      char[] Password = console.readpassword ("Password:");

      if (Username.equals ("Chris") && string.valueof (password). Equals ("Gohead")) {
       console.printf ("Welcome To Java application%1$s.\n ", username);
       The array should be emptied immediately after use to reduce its elapsed time in memory, enhanced security
        password = null;
       System.exit ( -1);
      } 
      else {
       console.printf ("Invalid username or password.\n");}}}

The above is small series for everyone to bring Java from the console reading data from several methods summed up all the content, hope to help you, a lot of support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.