软件编程
位置:首页>> 软件编程>> java编程>> 重新认识Java的System.in

重新认识Java的System.in

作者:isea533  发布时间:2023-08-24 01:55:18 

标签:java,system.in

重新认识 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.java
java 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();
    }
  }
}

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

来源:https://blog.csdn.net/isea533/article/details/70186811

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com