0

I'm writing code which deletes a word out of a text file when the user inputs it but I cant seem to get the scanner part to work

public static void Option2Method() throws IOException 
{

File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader =  new Scanner(inputFile); 
Scanner writer =new Scanner(tempFile);
String currentLine;

while((currentLine = reader.nextLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.print(currentLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}

2 Answers2

1

Scanner is not meant to write files, hence does not have a write() method. You can use BufferedWriterinstead.

Example:

public static void Option2Method() throws IOException {

    File inputFile = new File("wordlist.txt");
    FileWriter fstream = new FileWriter("TempWordlist.txt", true);
    BufferedWriter writer = new BufferedWriter(fstream);

    File tempFile = new File("TempWordlist.txt");
    String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
    Scanner reader = new Scanner(inputFile);

    while (reader.hasNextLine()) {
        String trimmedLine = reader.nextLine().trim();
        if (trimmedLine.equals(lineToRemove))
            continue;

        writer.write(trimmedLine + "\n");
    }

    reader.close();
    writer.close();
    inputFile.delete();
    tempFile.renameTo(inputFile);
}

Using PrintWriter:

    File inputFile = new File("wordlist.txt");
    PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("TempWordlist.txt", true)));

    File tempFile = new File("TempWordlist.txt");
    String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
    Scanner reader = new Scanner(inputFile);

    while (reader.hasNextLine()) {
        String trimmedLine = reader.nextLine().trim();
        if (trimmedLine.equals(lineToRemove))
            continue;

        writer.print(trimmedLine + "\n");
    }

    reader.close();
    writer.close();
    inputFile.delete();
    tempFile.renameTo(inputFile);
Tiago
  • 3,113
  • 2
  • 31
  • 45
0

Scanner doesn't have a print method. It is used to scan a file and read data from it.

If you want to write to a file, use this or that or just google "java write to file"

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61