我对用java为控制台命令行(Bash)应用程序创建一个通用的"管道"方法的想法感到困惑,这样基本上就可以执行像"ls-lt|head"这样的命令。
我无法专注于实现一个静态方法,比如说一个需要varargs方法的方法。。。给定上面的bash命令,它应该如下面的代码片段所示。
我的想法是将方法封装在Command对象中。
public static void pipe (Command ... commands) {
command1.execute();
command2.execute();
}
如有任何帮助,我们将不胜感激。
假设每个命令接受相同的输入并返回相同的内容。如果不是这种情况,您可以将一个对象作为输入并返回一个对象,每个命令都将强制转换。基本实现:
public static <T> T pipe(T input, Command<T>... commands) {
for (Command<T> com : commands) {
input = com.execute(input);
}
return input;
}
public interface Command<T> {
T execute(T input);
}
这也可以扩展到使用某个类型的列表,因此head
命令将始终存储并返回它获得的第一个输入(或前10个)。
无论如何,我不会自己实现。您应该看看java8流。管道/流是一系列聚合操作。
对于你的问题,答案是:
List<Path> lsFirst = Files.list(Paths.get("/")).limit(10).collect(Collectors.<Path>toList());
System.out.println(lsFirst);