Java: Scanner stopping at new line

I am trying to scan through text files and add them to a map, the map and everything is working. However, the scanner seems to be stopping when it comes to a 'enter' in the text file, or a blank line. This is my problem

here is my block of code for the scanner/mapper

class OneButtonListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent evt)
    {
        final JFileChooser oneFC = new JFileChooser();
        oneFC.showOpenDialog(AnalysisFrame.this);
        String newLine = null;
        oneFC.getName(null);
        int returnVal = 0;
        File fileOne = oneFC.getSelectedFile();

        Scanner input = null;        
        try {
            input = new Scanner(fileOne);
        } 
        catch (FileNotFoundException ex) {
            Logger.getLogger(AnalysisFrame.class.getName()).log(Level.SEVERE, null,
                            ex);
        }                       
        inputText = input.nextLine(); 
        String[] words = inputText.split("[ ntr,.;:!?(){}]");

        for(int i = 0; i < words.length; i++){
            key = words[i].toLowerCase(); 

            if (words[i].length() > 1){
                if (mapOne.get(key) == null){
                    mapOne.put(key, 1);
                }
                else {
                    value1 = mapOne.get(key).intValue();
                    value1++;
                    apOne.put(key, value1);
                }
            } 
         }
     }
}

Thanks for any help!


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("[ ntr,.;:!?(){}]");
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();
链接地址: http://www.djcxy.com/p/96058.html

上一篇: 扫描仪的nextLine(),仅获取部分

下一篇: Java:扫描仪停在新线上