首页 > 开发 > Java > 正文

重新认识Java的System.in

2019-10-21 18:42:11
字体:
来源:转载
供稿:网友

重新认识 Java 的 System.in

以前也写过不少命令行的程序,处理文件时总需要通过参数指定路径,直到今天看资料时发现了一种我自己从来没用过的方式。这种方式让我重新认识了System.in。

下面是一个简单的Cat 命令的例子,这里提供了-n参数用于配置是否显示行号。

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;public class Cat {  public static void main(String[] args) throws IOException {    //是否显示行号,使用参数 -n 启用    boolean showNumber = args.length > 0 && Arrays.asList(args).contains("-n");    int num = 0;    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));    String line = reader.readLine();    while (line != null) {      if (showNumber) {        num++;        System.out.printf("%1$8s %2$s%n", num, line);      } else {        System.out.println(line);      }      line = reader.readLine();    }  }}

这个方法中用到了参数,参数只用于判断是否存在-n这个参数,没有通过参数指定文件。

这里获取文件内容的方式就是 System.in,从输入流中读取。输入流中怎么提供文件内容呢?

就是通过输入重定向到命令。针对上面的 Cat.java 文件执行下面的命令:

javac Cat.javajava Cat -n < Cat.java

先使用 javac 编译,在通过 java 命令执行,通过输入重定向将Cat.java 作为命令的输入流。

上面命令执行后,输出内容如下:

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Cat {   public static void main(String[] args) throws IOException {     boolean showNumber = args.length > 0 && Arrays.asList(args).contains("-n");     int num = 0;     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));     String line = reader.readLine();     while (line != null) {       if (showNumber) {         num++;         System.out.printf("%1$8s %2$s%n", num, line);       } else {         System.out.println(line);       }       line = reader.readLine();     }   } }

如果只是处理文件,和参数方式指定文件路径没太大的区别。但是如果通过管道方式,就可以很方便的将前面命令的输出流作为输入流继续进行处理。例如下面的命令:

java Cat -n < Cat.java | java Cat -n

前一个命令的输出会作为第二个命令的输入,这会在原有行号的基础上增加一个行号,结果如下:

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Cat {   public static void main(String[] args) throws IOException {     boolean showNumber = args.length > 0 && Arrays.asList(args).contains("-n");     int num = 0;     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));     String line = reader.readLine();     while (line != null) {       if (showNumber) {        num++;         System.out.printf("%1$8s %2$s%n", num, line);       } else {         System.out.println(line);       }       line = reader.readLine();     }   } }

合理使用这种方式可以在某些情况下起到良好的作用。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对CuoXin错新网的支持。


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表