0

此方法用于将单词添加到 txt 文件然后对其进行排序,但我不允许在我的课程中使用缓冲阅读器功能。是否可以使用扫描仪来做到这一点

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);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String inputLine;
    List<String> lineList = new ArrayList<String>();
    while ((inputLine = bufferedReader.readLine()) != 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();

}

4

1 回答 1

0

你当然可以。BufferedReader这是使用和的等效代码Scanner

public void bufferedReaderVersion() throws Exception{
    File f = new File("filePath");
    Reader reader = new FileReader(f);
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line = null;

    while((line = bufferedReader.readLine()) != null){
        System.out.println(line);
    }

    bufferedReader.close();
    reader.close();
}

public void scannerVersion() throws Exception{
    File f = new File("filePath");
    Scanner sc = new Scanner(f);

    while(sc.hasNext()){
        System.out.println(sc.nextLine());
    }

    sc.close();
}
于 2013-03-28T12:10:53.017 回答