2

我有一种方法可以以单词列表格式从文本文件中删除单词,但它会不断删除文件中的所有数据而不是特定单词

 public static void Option2Method() throws IOException 
 {
   File inputFile = new File("wordlist.txt");
   File tempFile = new File("TempWordlist.txt");

   BufferedReader reader = new BufferedReader(new FileReader(inputFile));
   BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

   String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
   String currentLine;

   while((currentLine = reader.readLine()) != null)
 {
   String trimmedLine = currentLine.trim();
   if(trimmedLine.equals(lineToRemove)) continue;
   writer.write(currentLine);
 }
   boolean successful = tempFile.renameTo(inputFile);
 }
4

4 回答 4

1

代码必须调用close()作者。

确保数据从缓冲区获取到实际文件:

 while((currentLine = reader.readLine()) != null)
 {
   String trimmedLine = currentLine.trim();
   if(trimmedLine.equals(lineToRemove)) continue;
   writer.write(currentLine);
 }

 writer.close();
 reader.close();

考虑使用 try/catch/finally 块来确保即使在IOException抛出 an 时也关闭流。

于 2013-03-27T18:06:48.847 回答
0

尝试这个:

String str = "Sample Line";
String[] words = str.split(" "); 
for(i=0 to i>arr.length)
{
if(str.indexOf(arr[i])!=-1) //checks if the word is present...
str.replace(arr[i],""); //replace the stop word with a blank
space..
}

或者这样:

String yourwordline = "dgfhgdfdsgfl Sample dfhdkfl"; 
yourwordline.replaceAll("Sample",""); 
于 2013-03-27T18:10:11.250 回答
0

尝试这个:

public static void removeLineMethod(String lineToRemove) throws IOException {
   File inputFile = new File("wordlist.txt");
   File tempFile = new File("TempWordlist.txt");

   BufferedReader reader = new BufferedReader(new FileReader(inputFile));
   BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
   String currentLine;

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

如果你不删除输入文件,你的重命名将失败,所以关闭流,删除输入文件,然后重命名临时文件。

于 2013-03-27T18:10:14.600 回答
0
File inputFile = new File("wordlist.txt");
       File tempFile = new File("TempWordlist.txt");

   BufferedReader reader = new BufferedReader(new FileReader(inputFile));
   BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

   String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
   String currentLine;

 while((currentLine = reader.readLine()) != null)
 {
   String trimmedLine = currentLine.trim();
   if(trimmedLine.equals(lineToRemove)) continue;
   writer.write(currentLine);
   writer.newLine();
 }
   reader.close();
   writer.close();
   inputFile.delete();
   tempFile.renameTo(inputFile);
    }
于 2013-03-27T18:14:04.320 回答