Java从控制台读入数据的几种方法总结
作者:jingxian 发布时间:2022-03-23 07:40:18
标签:java,控制台,读入,数据
这里记录Java中从控制台读入信息的几种方式,已备后查!
(1)JDK 1.4(JDK 1.5和JDK 1.6也都兼容这种方法)
public class TestConsole1 {
public static void main(String[] args) {
String str = readDataFromConsole("Please input string:);
System.out.println("The information from console: + str);
}
/**
* Use InputStreamReader and System.in to read data from console
*
* @param prompt
*
* @return input string
*/
private static String readDataFromConsole(String prompt) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
try {
System.out.print(prompt);
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
(2)JDK 1.5(利用Scanner进行读取)
public class TestConsole2 {
public static void main(String[] args) {
String str = readDataFromConsole("Please input string:");
System.out.println("The information from console:" + str);
}
/**
* Use java.util.Scanner to read data from console
*
* @param prompt
*
* @return input string
*/
private static String readDataFromConsole(String prompt) {
Scanner scanner = new Scanner(System.in);
System.out.print(prompt);
return scanner.nextLine();
}
}
Scanner还可以很方便的扫描文件,读取里面的信息并转换成你要的类型,比如对“2 2.2 3.3 3.33 4.5 done”这样的数据求和,见如下代码:
public class TestConsole4 {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("num.txt");
fw.write("2 2.2 3.3 3.33 4.5 done");
fw.close();
System.out.println("Sum is "+scanFileForSum("num.txt"));
}
public static double scanFileForSum(String fileName) throws IOException {
double sum = 0.0;
FileReader fr = null;
try {
fr = new FileReader(fileName);
Scanner scanner = new Scanner(fr);
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
sum = sum + scanner.nextDouble();
} else {
String str = scanner.next();
if (str.equals("done")) {
break;
} else {
throw new RuntimeException("File Format is wrong!");
}
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File " + fileName + " not found!");
} finally {
if (fr != null)
fr.close();
}
return sum;
}
}
(3)JDK 1.6(利用java.io.Console进行读取)
JDK6中提供了java.io.Console类专用来访问基于字符的控制台设备.
你的程序如果要与Windows下的cmd或者Linux下的Terminal交互,就可以用Console类代劳.(类似System.in和System.out)
但我们不总是能得到可用的Console, 一个JVM是否有可用的Console依赖于底层平台和JVM如何被调用.
如果JVM是在交互式命令行(比如Windows的cmd)中启动的,并且输入输出没有重定向到另外的地方,那么就可以得到一个可用的Console实例。
在使用 IDE 的情况下,是无法获取到Console实例的,原因在于在 IDE 的环境下,重新定向了标准输入和输出流,也是就是将系统控制台上的输入输出重定向到了 IDE 的控制台中
public class TestConsole3 {
public static void main(String[] args) {
String str = readDataFromConsole("Please input string:");
System.out.println("The information from console:" + str);
}
/**
* Use java.io.console to read data from console
*
* @param prompt
*
* @return input string
*/
private static String readDataFromConsole(String prompt) {
Console console = System.console();
if (console == null) {
throw new IllegalStateException("Console is not available!");
}
return console.readLine(prompt);
}
}
Console类还有个特色就是,专门对密码(输入无回显)等安全字符,进行了处理。专门提供 readPassword()方法,具体应用见如下代码:
public class TestConsole5 {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
throw new IllegalStateException("Console is not available!");
}
while(true){
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");
if (username.equals("Chris") && String.valueOf(password).equals("GoHead")) {
console.printf("Welcome to Java Application %1$s.\n", username);
// 使用后应立即将数组清空,以减少其在内存中占用的时间,增强安全性
password = null;
System.exit(-1);
}
else {
console.printf("Invalid username or password.\n");
}
}
}
}


猜你喜欢
- 先看代码public class MaxHuiWen {public static void main(String[] args) { &
- 目录前言整合swagger api自定义配置信息简单使用Swagger常用注解Api标记ApiOperation标记ApiParam标记Ap
- 1.pom.xml文件引入druid和数据库连接jar包<properties><druid.version>1.0
- Android实现九宫格图案解锁,自带将图案转化成数字密码的功能,代码如下:LockPatternView.javapackage com.
- 使用限制JDBC未支持列表Sharding-JDBC暂时未支持不常用的JDBC方法。DataSource接口不支持timeout相关操作Co
- JSTL条件行为和遍历行为JSTL的条件行为标签有四个:if,choose,when,otherwise标签1、if标签是对某一个条件进行测
- 要爬取一个网站遇到了极验的验证码,这周都在想着怎么破解这个,网上搜了好多知乎上看到有人问了这问题,我按照这思路去大概实现了一下。1.使用ht
- 一、为什么要编码不知道大家有没有想过一个问题,那就是为什么要编码?我们能不能不编码?要回答这个问题必须要回到计算机是如何表示我们人类能够理解
- 什么是雪花算法雪花算法的本质为生成一个64位长度的具有自增性的分布式全局唯一id。在64bits中,会对不同段的位进行划分。可分为:符号段时
- 一、简介现在的Android应用程序中,不可避免的都会使用到图片,如果每次加载图片的时候都要从网络重新拉取,这样不但很耗费用户的流量,而且图
- 本文主要是对Handler和消息循环的实现原理进行源码分析,如果不熟悉Handler可以参见博文《详解Android中Handler的使用方
- Java 的表格表格是一个由多行,多列组成的二维显示区。Swing的JTable以及相关类提供了对这种表格的支持,程序既可以使用简单的代码创
- Java 垃圾回收与对象生命周期详解Java中的垃圾回收与对象生命周期1. 垃圾回收 垃圾回收是Java程序设计中
- 本文实例总结了C#中string.format用法。分享给大家供大家参考。具体分析如下:String.Format 方法的几种定义:Stri
- 本文实例为大家分享了PopupWindow实现自定义overflow的具体代码,供大家参考,具体内容如下当Action Bar的Action
- 本文实例为大家分享了C#实现图表中鼠标移动并显示数据的具体代码,供大家参考,具体内容如下效果图:1.首先在页面上添加一个label控件并 默
- java中javaBean与Bean的深入理解JavaBean 是Java中的一种特殊的类,可以将多个对象封装到一个对象(bean)中。特点
- 抛砖今天使用monio做S3存储时,添加云服务器初始化时一直在构建客户端抛出异常。MinioClient.builder() //NoCla
- 问题分析疑惑满满小枫听到这个面试题的时候,心想这是什么水面试官,怎么问这么简单的题目,心想一个for循环加上equal判断再删除不就完事了吗
- ImageCacheconst int _kDefaultSize = 1000;const int _kDefaultSizeBytes