Reputation:
I have a method to remove a word from a text file in list format of words but it keep deleting all the data in the file instead of the specific word
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);
}
Upvotes: 2
Views: 6138
Reputation: 5661
The code must call close()
on the writer.
Make sure the data gets from the buffer to the actual file:
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
reader.close();
Consider using try/catch/finally blocks to make sure the streams are closed even when an IOException
is thrown.
Upvotes: 1
Reputation: 2363
Try this:
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..
}
Or this way:
String yourwordline = "dgfhgdfdsgfl Sample dfhdkfl";
yourwordline.replaceAll("Sample","");
Upvotes: 0
Reputation: 1765
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);
}
Upvotes: 0
Reputation: 3687
Try this:
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);
}
if you do not delete the input file, your rename will fail, so close the streams, delete the input file, then rename the temp file.
Upvotes: 0