从文本文件中删除单词

时间:2013-03-27 17:56:00

标签: java file text

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

 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 个答案:

答案 0 :(得分: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也会关闭流。

答案 1 :(得分: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",""); 

答案 2 :(得分: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);
 }

如果不删除输入文件,则重命名将失败,因此请关闭流,删除输入文件,然后重命名临时文件。

答案 3 :(得分: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);
    }