Java:扫描仪停在新线上

我正在尝试扫描文本文件并将它们添加到地图,地图和一切正在工作。 但是,当涉及到文本文件中的“输入”时,扫描器似乎停止工作,或者空白行。 这是我的问题

这里是我的扫描仪/映射器的代码块

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);
                }
            } 
         }
     }
}

谢谢你的帮助!


您应该在循环内进行扫描,直到它到达文件末尾,例如:

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

使用split的另一种方法是使用Scanner使用分隔符,并使用hasNext()next()而不是hasNextLine()nextLine() 。 试试看,看看它是否有效。

例如:

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

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

另外,请注意,不必每次都创建JFileChooser

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

    @Override
    public void actionPerformed(ActionEvent evt)
    {

在很长一段时间里没有和Java一起工作,我可能会离开,但它看起来像你调用inputText = input.nextLine(); 只有一次,所以你只得到一条线是有道理的。 大概你想在一个循环中调用nextLine() ,以便它一直给你直线,直到它到达文件的末尾。


String contentsOfWholeFile = new Scanner(file).useDelimiter("Z").next();
链接地址: http://www.djcxy.com/p/96057.html

上一篇: Java: Scanner stopping at new line

下一篇: How to remove line breaks from a file in Java?