技术控

    今日:17| 主题:51423
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Interactive Console Applications in Java

[复制链接]
石头也很帅 发表于 2016-11-27 21:58:42
137 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Console applications come in several different forms:
  
       
  • Applications having a text user interface that provides a GUI-like experience by using text-based components such as windows, dialogs, menus, text fields and buttons.  
  Examples include the file manager    Midnight Commander, the Linux tool    menuconfig, or the    Lynxbrowser.  
  For developing such applications, you can use one of the following Java libraries:    Lanterna,    Charva, or    Java Curses.  
  
       
  • Programs that take all input as command-line arguments. Most commands in Unix-like operating systems belong to this category.  
  Many Java libraries for parsing command-line arguments exist:    Apache Commons-CLI,    JOpt Simple,    args4j,    JCommander,    Jewel CLI, and many other.  
  
       
  • Command-line interface shells, where the user issues commands to the program in the form of successive lines of text.  
  Examples include Unix shells such as    bash, or    REPLenvironments such as    JShell, which is planned to be included in Java 9.  
  The Java libraries    Spring Shelland    Clichehelp creating this kind of applications.  
  
       
  •       Interactive console applications that prompt the user to provide information. Instead of issuing commands as in the case of shell applications, the user controls the program in a more limited way, by specifying some parameter values or choosing an option from a list.
      
  The last type of console applications in the above list is the typical choice when starting to learn a new programming language. However, people tend to switch to one of the other types when implementing "serious" console applications. If the number of input parameters is relatively small, programs taking the input as command-line arguments are preferred, in order to allow pipelining. Otherwise, a shell interface or a GUI-like text interface are usually more appropriate.
  So, are interactive console applications that prompt for user input still relevant today, or are they on the brink of extinction? I assume that many such applications are still written, but they usually don't end up being widely known, because they are mostly created for personal use or as prototypes.
  If you decide to write such an application, you have to read user input in an interactive manner. What is the best way to do this in Java? Let's look at the most frequently used approaches:
  
       
  • Wrapping the standard input stream in a      BufferedReader and reading user input line by line:  
  1. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  2. String line = reader.readLine();
复制代码
It is your responsibility to parse the input.
  
       
  • Using a      java.util.Scanner, which provides methods for parsing primitive types and strings using regular expressions:  
  1. Scanner scanner = new Scanner(System.in);
  2. String productId = scanner.next("[A-Z]{3}-[0-9]{5}");
  3. int quantity = scanner.nextInt();
  4. float price = scanner.nextFloat();
复制代码

       
  • Using a      java.io.Console, which allows you to read not only ordinary text, but also passwords, by suppressing echoing:  
  1. Console console = System.console();
  2. String user = console.readLine("user: ");
  3. String password = new String(console.readPassword("password: "));
复制代码
Console does not provide methods for parsing the input.
  All of the above methods have drawbacks. An ideal solution would allow both parsing the input and reading passwords. If your application needs to read sensitive data, you are forced to use a java.io.Console, because there is no easy way to suppress echoing for the standard input stream. Aside of the annoying fact that you have to parse yourself the input, there is another problem with this solution: your virtual machine may not have a Console. This happens if the virtual machine has not been started from an interactive command line or if the standard input and output streams have been redirected. When running your application in an IDE,    System.console()     usually returns null.  
  Console is a final class with a private constructor. A virtual machine has at most one instance of this class, which can be obtained by invoking    System.console(). You cannot provide your own Console implementation. What you can do instead, is to introduce an abstraction layer that provides the same functionality. By writing code that interacts only with this abstraction layer and not directly with a Console instance, you can handle the case of    System.console()returning null.  
  This is the approach I took to develop    Text-IO, a library for creating interactive console applications. The abstraction layer, which in Text-IO is represented by the    TextTerminalinterface, is extremely simple: a text terminal is only required to provide methods for printing a line of text and for reading a line of text, optionally masking the input. By default, the Text-IO library tries to use a text terminal backed by the java.io.Console. If the virtual machine has no console device, a Swing-based terminal is used instead. (The mechanism for    choosing a text terminalis actually more complex and provides a Service Provider Interface for configuring additional text terminals.)  
  Some other useful features of the Text-IO library include:
  
       
  • Support for reading values with various data types.   
  • The ability to specify default values.   
  • The ability to specify constraints on the input values (format patterns, value ranges, length constraints etc.).   
  • The ability to select one or more values from a list.   
  • The ability to customize the error messages.  
  The code fragment below illustrates the use of Text-IO:
  1. TextIO textIO = TextIoFactory.getTextIO();
  2. String user = textIO.newStringInputReader()
  3.         .withDefaultValue("admin")
  4.         .read("Username");
  5. String password = textIO.newStringInputReader()
  6.         .withMinLength(6)
  7.         .withInputMasking(true)
  8.         .read("Password");
  9. int age = textIO.newIntInputReader()
  10.         .withMinVal(13)
  11.         .read("Age");
  12. Month month = textIO.newEnumInputReader(Month.class)
  13.         .read("What month were you born in?");
  14. textIO.getTextTerminal().println("\nUser " + user + " is " + age + " years old, " +
  15.         "was born in " + month + " and has the password " + password + ".");
复制代码
An example session using the above code produces the following output:
  1. Username [admin]:
  2. Password: ****
  3. Invalid value.
  4. Expected a string with at least 6 characters.
  5. Password: ******
  6. Age: 9
  7. Invalid value.
  8. Expected an integer value greater than or equal to 13.
  9. Age: 19
  10. What month were you born in?
  11. 1: JANUARY
  12. 2: FEBRUARY
  13. 3: MARCH
  14. 4: APRIL
  15. 5: MAY
  16. 6: JUNE
  17. 7: JULY
  18. 8: AUGUST
  19. 9: SEPTEMBER
  20. 10: OCTOBER
  21. 11: NOVEMBER
  22. 12: DECEMBER
  23. Enter your choice: 5
  24. User admin is 19 years old, was born in MAY and has the password 123456.
复制代码
Click    hereto see an animated image of this example session in a Swing-based console.  
  A further advantage of using    Text-IOis that you can easily test your code by implementing a mock text terminal that provides the desired input for your test case.
友荐云推荐




上一篇:HTTP2.0关于Server Push的研究
下一篇:Controlling a Game Room with Amazon Echo
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表