【问题标题】:Scanner text file扫描仪文本文件
【发布时间】:2013-04-06 17:59:33
【问题描述】:

我正在为一个程序编写代码,该程序从文本文件中获取单词并将它们按字母顺序排列,但我似乎无法让扫描仪工作?

public static void Option1Method() throws IOException {
    FileWriter aFileWriter = new FileWriter("wordlist.txt", true);
    PrintWriter out = new PrintWriter(aFileWriter);
    String word = JOptionPane.showInputDialog(null, "Enter a word");

    out.println(word);
    out.close();

    aFileWriter.close();

    String inputFile = "wordlist.txt";
    String outputFile = "wordlist.txt";
    FileReader fileReader = new FileReader(inputFile);
    Scanner scan = new Scanner(fileReader);
    scan.nextLine;
    String inputLine;
    List<String> lineList = new ArrayList<String>();
    while ((inputLine = scan.nextLine()) != null) {
        lineList.add(inputLine);
    }
    fileReader.close();

    Collections.sort(lineList);

    FileWriter fileWriter = new FileWriter(outputFile);
    PrintWriter out1 = new PrintWriter(fileWriter);
    for (String outputLine : lineList) {
        out1.println(outputLine);
    }
    out1.flush();
    out1.close();
    fileWriter.close();
}

【问题讨论】:

    标签: java file text nosuchelementexception


    【解决方案1】:

    Scanner#nextLine 是一种方法。您需要添加括号。替换

    scan.nextLine;
    

    与

    scan.nextLine();
                 ^
    

    同样Scanner 使用hasNextLine 来检查后续行。在打开的文件上调用scan.nextLine() 最终会导致NoSuchElementException。替换:

    while ((inputLine = scan.nextLine()) != null) {
      ...
    }
    

    与

    while (scan.hasNextLine()) {
       inputLine = scan.nextLine();
       lineList.add(inputLine);
    }
    

    请注意,第一次调用scan.nextLine() 会导致第一行被使用,而不是写入排序的输出文件。如果您打算将所有单词写入文件,请删除或注释此行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      相关资源
      最近更新 更多