There are three ways to share input on a Java character terminal

  • 2020-04-01 02:32:18
  • OfStack

There are three ways to get input on a Java character terminal:

1. Java. lang. system. in (currently supported by JDK versions)
2. Java. util.Scanner (JDK version > = 1.5)
3. Java.io.Console(JDK version > =1.6), features: can not echo password characters

Reference:
Here are several ways in which information can be read from the console in Java
(1)JDK 1.4(both JDK 1.5 and JDK 1.6 are also compatible with this approach)


public class TestConsole1 {  
    public static void main(String[] args) {  
        String str = readDataFromConsole("Please input string : );  
        System.out.println("The information from console :  + str);  
    }  

      
    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 by Scanner)


public class TestConsole2 {  
    public static void main(String[] args) {  
        String str = readDataFromConsole("Please input string:");  
        System.out.println("The information from console:" + str);  
    }  

      
    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 file, read the information inside and convert it to the type you want, such as "2 2.2 3.3 3.33 4.5 done" such as data sum, see the following code:


public class TestConsole4 {  

    public static void main(String[] args) throws IOException {  
        FileWriter fw = new FileWriter("num.txt");  
        fw.write("2 2.2 3.3 3.33 4.5 done");  
        fw.close();  

        System.out.println("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 using java.io.console)
JDK6 provides the java.io.console class for accessing character-based Console devices.
If your program wants to interact with Windows CMD or Linux Terminal, you can use the Console class instead.
But we don't always have available consoles, and whether a JVM has one depends on the underlying platform and how the JVM is invoked.
If the JVM is started on the interactive command line (such as CMD for Windows), and the input and output are not redirected elsewhere, you get an available Console instance.
In the case of an IDE, the Console instance cannot be obtained because in the IDE environment, the standard input and output streams are redirected, that is, the input and output from the system Console are redirected to the IDE Console


public class TestConsole3 {  
    public static void main(String[] args) {  
        String str = readDataFromConsole("Please input string:");  
        System.out.println("The information from console:" + str);  
    }  

      
    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 handles security characters such as passwords (enter without echo). The readPassword() method is specially provided, and the specific application is shown in 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);  
             //Clean the array immediately after use to reduce its time in memory and enhance security & NBSP;  
                password = null;  
              System.exit(-1);  
            }   
            else {  
              console.printf("Invalid username or password.n");  
            }  
            }  
          }  

}  


Related articles: