Buffered Reader Change

2020-05-06 05:31发布

问题:

Hi I want to replace the BufferedReader in the piece of code with scanner?? I wrote this code but then realized that we're not allowed use bufferedreader. But Havent a clue how to even go about,

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

回答1:

Take a look at the definitions for hasNextLine and nextLine in the Scanner class.

Although new Scanner(fileReader) works, you could rather pass the file name directly into the Scanner's constructor.