java输入输出

读取终端输入

在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类结构

主要分为字符流和字节流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值