我很困惑在java中为我的控制台命令行(Bash)应用程序创建一个通用的“管道”方法,所以基本上可以执行像“ls -lt | head”这样的命令。
我不能完全实现让我们说一个静态方法,它会采用varargs方法...给出上面的bash命令,它应该如下面的代码片段所示。
我的想法是在Command对象中封装方法。
public static void pipe (Command ... commands) {
command1.execute();
command2.execute();
}
任何帮助都将受到高度赞赏。
答案 0 :(得分:3)
假设每个命令采用相同的输入并返回相同的内容。如果不是这种情况,您可以将对象作为输入并返回一个对象,并且每个Command都将被强制转换。基本实现:
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个)。
无论如何我不会自己实施。你应该看看java 8流。管道/流是一系列聚合操作。
对于你的问题,答案就像是:
List<Path> lsFirst = Files.list(Paths.get("/")).limit(10).collect(Collectors.<Path>toList());
System.out.println(lsFirst);