What is the difference in these ways to read in user-input?

Deadly 提交于 2019-11-27 18:48:36

问题


I came across this topic How to get basic user input for java and although the answer for this particular question was sufficient, I wondered why there are so many different ways to read in user-input. In particular what are the pros and cons of these different ways to read in user-input? When would it make sense to use one over the other?

These where the possible ways mentioned in that post.

  1. Scanner class
  2. BufferedReader and InputStreamReader classes
  3. DataInputStream class
  4. Console class

回答1:


They're all intended for use in different things. I'll do my best to explain, but I didn't totally understand the docs and I haven't used each of these extensively, so if you spot any mistakes please let me know.

  1. The Scanner class is meant to process input from just about any stream and give the developer a nice, easy way to manage it without learning too many classes. It's fairly basic, but most of the time, it's plenty enough -- for example, if you just want to get user input in a simple-to-learn way, Scanner is what you want.

  2. The BufferedReader class is meant to read from files quickly, at the expense of memory. It's meant to be a wrapper around other, simpler classes like FileInputStream (technically, any class which extends InputStream) and, by buffering the next few bytes and reading from that array instead of directly the stream, and only reading from the stream when it reaches the end of the buffer. If you're more interested in speed than low memory usage, you'll want this -- though it really doesn't use much more memory unless you explicitly tell it to.

  3. DataInputStream is a more general input class for data. It's if you just want to read primitives from a stream -- rather than reading individual bits directly and composing the respective types, this provides a simple method to do that for you. This page is where the docs say to go for more information about how the methods actually work.

  4. The Console class is explicitly for a command line interface (CLI) program -- that is, for reading data from and writing data to a console. It's like Scanner -- a simple, easy-to-learn class for doing basic tasks.

In a sentence, they're meant for different tasks, and which one you use should be determined by what you're trying to do.




回答2:


Scanner is the most friendly input Reader in Java and i like it! BufferedReader and InputStreamReader are both for input Reader and Worked also with filing,some thing like writing readable inputs to a file and etc.. and i don't use two others because the most important IO classes are Scanner and BufferedReader ... you can also Use System.IO for reading inputs but i prefer Scanner for myself



来源:https://stackoverflow.com/questions/27601520/what-is-the-difference-in-these-ways-to-read-in-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!