I want to delete a specific line from a text file. I found that line, but what to do next? Any idea?
6 Answers
There is no magic to removing lines.
- Copy the file line by line, without the line you don't want.
- Delete the original file.
- rename the copy as the original file.
1 Comment
Peter Lawrey
You make a new file by writing to a file which doesn't exist. You can append an extension like
.new to create a new file. You can rename it with File.rename()Try this code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Solution {
public static void main(String[] args) throws FileNotFoundException, IOException{
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
Comments
Try to read file:
public static String readAllText(String filename) throws Exception {
StringBuilder sb = new StringBuilder();
Files.lines(Paths.get(filename)).forEach(sb::append);
return sb.toString();
}
then split text from specific character (for new line "\n")
private String changeFile(){
String file = readAllText("file1.txt");
String[] arr = file.split("\n"); // every arr items is a line now.
StringBuilder sb = new StringBuilder();
for(String s : arr)
{
if(s.contains("characterfromlinewillbedeleted"))
continue;
sb.append(s); //If you want to split with new lines you can use sb.append(s + "\n");
}
return sb.toString(); //new file that does not contains that lines.
}
then write this file's string to new file with:
public static void writeAllText(String text, String fileout) {
try {
PrintWriter pw = new PrintWriter(fileout);
pw.print(text);
pw.close();
} catch (Exception e) {
//handle exception here
}
}
writeAllText(changeFile(),"newfilename.txt");
1 Comment
Tarık İNCE
You should change here "characterfromlinewillbedeleted" to what you lines will be deleted have.
Deleting a text line directly in a file is not possible. We have to read the file into memory, remove the text line and rewrite the edited content.
2 Comments
Simon Nickerson
Although, of course, it isn't necessary that the entire file fits into memory, as you can read and write in the same loop.
Andreas Dolk
@Simon - agreed - we don't have to store the entire file in memory but, at the end, every single byte of the file has been read, buffered somewhere in the RAM and written to the new target file.
Maybe a search method would do what you want i.e. "search" method takes a string as a parameter and search for it into the file and replace the line contains that string.
PS:
public static void search (String s)
{
String buffer = "";
try {
Scanner scan = new Scanner (new File ("filename.txt"));
while (scan.hasNext())
{
buffer = scan.nextLine();
String [] splittedLine = buffer.split(" ");
if (splittedLine[0].equals(s))
{
buffer = "";
}
else
{
//print some message that tells you that the string not found
}
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("An error occured while searching in file!");
}
}