标签:
1、使用System.in.read读取,使用System.out.println 输出
1 package org.zln.io; 2 3 import java.io.IOException; 4 5 /** 6 * Created by coolkid on 2015/6/21 0021. 7 */ 8 public class TestSystemInReadString { 9 public static void main(String[] args) throws IOException { 10 byte[] bytes = new byte[100]; 11 int len = 0; 12 System.out.println("开始读取"); 13 while ((len = System.in.read(bytes))>0){ 14 System.out.println("len:"+len); 15 System.out.write(bytes, 0, len); 16 if (len>=4&&"exit".equalsIgnoreCase(new String(bytes,0,4))){ 17 break; 18 } 19 } 20 System.out.println("结束读取"); 21 } 22 }
分析:上述代码存在缺陷,就是每次(行)读取的数据不能超过100字符,超过部分会被舍弃。
2、使用System.console.readLine读取
1 package org.zln.io; 2 3 /** 4 * Created by coolkid on 2015/6/21 0021. 5 */ 6 public class TestConsole { 7 public static void main(String[] args) { 8 while (true){ 9 System.out.print("开始读取:"); 10 String s = System.console().readLine(); 11 System.out.println("read:"+s); 12 if (s.length()>3&&"exit".equalsIgnoreCase(s.substring(0,4))){ 13 break; 14 } 15 16 } 17 System.out.println("读取结束"); 18 } 19 }
分析:使用console类,必须在控制台中允许,不能在IDE。因为虚拟机是否具有控制台取决于底层平台,以及调用虚拟机的方式
3、密码的隐藏输入
1 private static void consoleReadPassword() { 2 while (true){ 3 String s = new String(System.console().readPassword("%s","请输入密码:")); 4 System.out.println("read:"+s); 5 if (s.length()>3&&"exit".equalsIgnoreCase(s.substring(0,4))){ 6 break; 7 } 8 9 } 10 System.out.println("读取结束"); 11 }
分析:效果与在Linux控制台中输入密码相同,就是不会显示输入的密码是多少,一定程度上防止密码泄露
标签:
原文地址:http://www.cnblogs.com/sherrykid/p/4591931.html