读取终端输入
在java字符终端上获取输入有三种方式
1、使用java.io.BufferedReader和java.io.InputStreamReader;
2、java.util.Scanner (JDK版本>=1.5)
3、java.io.Console(JDK版本>=1.6),特色:能不回显密码字符
方法1的示例
public class Sandbox4 extends Sandbox2{
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while(true){
try {
str = br.readLine();
}catch(IOException e){
e.printStackTrace();
}
if(str.equals("END"))break;
System.out.print(str);
}
}
}
方法2的示例
public class Sandbox4 extends Sandbox2{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = null;
while(true){
str = scanner.nextLine();
if(str.equals("END"))break;
System.out.println(str);
}
scanner.close();
}
}
方法3的示例
注意,在eclipse等IDE下不能使用这种该方法,因为JVM不是在命令行中被调用,输入输出被重定向了。
java写标准输出也有如下形式
public class Sandbox4 extends Sandbox2{
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
throw new IllegalStateException("Console is not available!");
}
String str = null;
while(true){
str = console.readLine("请输入");
if("END".equals(str))break;
System.out.println(str);
}
}
}
无论哪种方法,都需要
java.lang.System.in来创建输入流。
很多同学问,可不可以改变System.in输入流,比如说从文档输入而非控制台输入。其实是可以的
import java.lang.*;
public class SystemDemo {
public static void main(String[] args) throws Exception {
// existing file
System.setIn(new FileInputStream("file.txt"));
// read the first character in the file
char ret = (char)System.in.read();
// returns the first character
System.out.println(ret);
}
}
实际上,system.in就是一个inputstream类的子孙类的对象。所以,尽管可以这么做,我们也不推荐更改system.in中的默认输入流。
java io类结构
主要分为字符流和字节流