2013-04-07 87 views
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); 
} 
+0

当你有问题吗? – 2013-04-07 10:49:04

+0

给writer.print一个错误(currentLine +“\ n”);它说它找不到符号 – user2205055 2013-04-07 10:51:23

回答

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); 
+0

那么有没有办法用PrintWriter? – user2205055 2013-04-07 13:28:54

+0

是的。我已将它添加到答案中。 – Tiago 2013-04-07 17:00:56

0

Scanner没有print方法。它用于扫描一个文件和读取来自它的数据。

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

+0

是的,但我不允许使用BufferedReader,多数民众赞成在问题 – user2205055 2013-04-07 10:58:23

+1

你不需要BufferedReader,你需要BufferedWriter – BobTheBuilder 2013-04-07 10:59:45