1

我尝试编写一个带有自动完成功能的简单 Shell。我使用JLine图书馆。这是我的代码。

public class ConsoleDemo {
    public static void main(String[] args) {
        try {
            ConsoleReader console = new ConsoleReader();
            console.setPrompt(">>> ");
            console.addCompleter(new MyStringsCompleter("a", "aaa", "b", "bbb"));           
            String line;
            while ((line = console.readLine()) != null) {
                console.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

问题是当我按下时我的应用程序没有完成任何操作tab

>>> a [press tab]

如何正确使用它来自动完成我的输入?

UPD

public class MyStringsCompleter implements Completer {

    private final SortedSet<String> strings = new TreeSet<>();

    public MyStringsCompleter(Collection<String> strings) {
        this.strings.addAll(strings);
    }

    public MyStringsCompleter(String... strings) {
        this(asList(strings));
    }

    @Override
    public int complete(String buffer, int cursor, List<CharSequence> candidates) {
        if (buffer == null) {
            candidates.addAll(strings);
        } else {
            for (String match : strings.tailSet(buffer)) {
                if (!match.startsWith(buffer)) {
                    break;
                }
                candidates.add(match);
            }
        }
        if (candidates.size() == 1) {
            candidates.set(0, candidates.get(0) + " ");
        }
        return candidates.isEmpty() ? -1 : 0;
    }
}
4

2 回答 2

2

问题出在我的 IDE 中。当我不通过 IDE 启动我的应用程序时,一切正常。所以问题出在 IDE 中,它以某种方式拦截了控制台输入。

于 2015-01-29T16:13:18.197 回答
1

简单地添加字符串StringsCompleter不会完成你想要的。您必须使用completefrom 的方法StringsCompleter。一个例子可以在这里找到。

于 2015-01-28T15:08:56.813 回答