Java: Scanner stopping at new line

别等时光非礼了梦想. 提交于 2019-12-02 07:16:57

You should scan inside a loop until it reaches the end of the file, for example:

StringBuilder builder = new StringBuilder();
while(input.hasNextLine()){
    builder.append(input.nextLine());
    builder.append(" "); // might not be necessary
}
String inputText = builder.toString();

An alternative to using split could be to use a Delimiter with the Scanner and use hasNext() and next() instead of hasNextLine() and nextLine(). Try it out, see if it works.

For example:

scanner.useDelimiter("[ \n\t\r,.;:!?(){}]");
ArrayList<String> tokens = new ArrayList<String>();
while(scanner.hasNext()){
    tokens.add(scanner.next());
}

String[] words = tokens.toArray(new String[0]); // optional

Also on a side note, it's not necessary to create the JFileChooser everytime:

class OneButtonListener implements ActionListener
{
    private final JFileChooser oneFC = new JFileChooser();

    @Override
    public void actionPerformed(ActionEvent evt)
    {

Not having worked with Java in a very long time I may be way off, but it looks like you call inputText = input.nextLine(); exactly once, so it makes sense that you're only getting one line. Presumably you want to call nextLine() in a loop so that it keeps giving you lines until it gets to the end of the file.

String contentsOfWholeFile = new Scanner(file).useDelimiter("\\Z").next();

In split("[ \n\t\r,.;:!?(){}]") add \f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!