Java从控制台读入数据的几种方法总结

作者:jingxian 时间:2022-03-23 07:40:18 

这里记录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");
     }
     }
    }

}
标签:java,控制台,读入,数据
0
投稿

猜你喜欢

  • 基于Spring@Autowired注解与自动装配详谈

    2022-01-14 09:38:49
  • 基于struts2和hibernate实现登录和注册功能

    2022-03-23 00:27:43
  • RestTemplate文件上传下载与大文件流式下载

    2023-10-15 16:54:14
  • Java Mybatis框架Dao层的实现与映射文件以及核心配置文件详解分析

    2021-06-15 16:29:22
  • 基于Mybatis plus 自动代码生成器的实现代码

    2023-11-24 10:40:51
  • Android Studio使用小技巧:提取方法代码片段

    2023-11-14 19:35:20
  • Java中ArrayList与顺序表的定义与实现方法

    2022-06-08 03:27:12
  • 关于JDK8中的字符串拼接示例详解

    2021-10-27 13:38:59
  • SpringBoot使用Spark过程详解

    2021-07-30 06:19:21
  • springBoot系列常用注解(小结)

    2023-12-17 23:26:45
  • Java并发线程池实例分析讲解

    2022-08-05 20:25:40
  • Java线程池实现原理总结

    2023-04-15 02:37:11
  • Java 反射调用静态方法的简单实例

    2021-10-09 06:47:58
  • Springcloud Config配置中心使用与相关介绍

    2021-07-13 05:15:17
  • IntelliJ IDEA 的使用界面图文教程

    2022-10-01 17:24:59
  • 浅析Java SPI 与 dubbo SPI

    2021-10-23 16:54:12
  • C#实现图形位置组合转换的方法

    2022-01-23 17:29:35
  • Trie树(字典树)的介绍及Java实现

    2022-06-14 15:38:24
  • JDK8并行流及串行流区别原理详解

    2023-06-25 16:23:39
  • Android的RV列表刷新详解Payload与Diff方式异同

    2023-07-05 13:17:29
  • asp之家 软件编程 m.aspxhome.com