0

我正在编写代码,当用户输入它时从文本文件中删除一个单词,但我似乎无法让扫描仪部分工作

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

2 回答 2

1

Scanner不打算写文件,因此没有write()方法。你可以BufferedWriter改用。

例子:

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

使用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);
于 2013-04-07T11:02:48.613 回答
0

Scanner没有print方法。它用于扫描文件并从中读取数据。

如果你想写入文件,使用这个那个或者只是谷歌“ java write to file

于 2013-04-07T10:53:00.503 回答