Delete a Line from a File Using Java

Find a line in a file and remove it

This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.

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

How to delete or remove a specific line from a text file

Try this code:

public static void removeLine(BufferedReader br , File f,  String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));

}
bw.close();
br.close();
boolean delete = f.delete();
boolean b = temp.renameTo(f);
}

Remove specific line from txt file

If you want to remove a line by a line number I guess you can do a change to your code like this. You can give the int value of Id to the lineToRemove variable instead of my hard coded value

import java.io.*;

public class A {

public static void main(String[] args) throws IOException {
new A().useDelete();
}

public void useDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");

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

int lineToRemove = 2;
String currentLine;
int count = 0;

while ((currentLine = reader.readLine()) != null) {
count++;
if (count == lineToRemove) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
}

JAVA removing a line from a .txt file with a keyword

I've tested your code with minor changes (noted by @Andreas while I was writing this) and it works as expected

    public static void main(String[] args) {
try {

File inFile = new File("C:\\rirubio\\books.txt");

if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}

//Construct the new file that will later be renamed to the original filename.
File tempFile = new File("C:\\rirubio\\books.txt" + "_temp");

BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

String line = null;

String lineToRemove = JOptionPane.showInputDialog("Enter line to remove");

//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().contains(lineToRemove)) {
pw.println(line);
pw.flush();
}
}

pw.close();
br.close();

//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}

//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Java delete lines in a file?

Well, I think, what you are looking for is substring method. I believe there would be some reason why you have this requirement where you just have the code and you have to delete the next two lines of that set also. Please have a look at below code. It should work, given that the structure of your file is fixed and not going to change.

    String filePath = "C:/Users/taylo/Astronomy/Which Bright Stars Are Visible/StoreVerificationCodes.txt";
//Instantiating the Scanner class to read the file
Scanner sc = new Scanner(new File(filePath));
//instantiating the StringBuffer class
StringBuffer buffer = new StringBuffer();
//Reading lines of the file and appending them to StringBuffer
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
System.out.println("Contents of the file: "+fileContents);
//closing the Scanner object
sc.close();
String oldLine = "Code: 789678";
String newLine = "";

// My changes starts here.............
String codePattern = "Code:"; // A fixed pattern
int firstIndex = fileContents.indexOf(oldLine); // To get the index of code you looking for.
int nextIndex= fileContents.indexOf(codePattern, firstIndex+1);
if(nextIndex != -1) {
nextIndex = fileContents.indexOf(codePattern, firstIndex+1) -5;
fileContents = fileContents.substring(0, firstIndex) + fileContents.substring(nextIndex+3);
}
else
fileContents = fileContents.substring(0, firstIndex);
// My changes done here.............
//fileContents = fileContents.replaceAll(oldLine, newLine); //No need

FileWriter writer = new FileWriter(filePath);
System.out.println("");
System.out.println("new data: "+fileContents);
writer.append(fileContents);
writer.flush();
writer.close();

Delete last line in text file

If you wanted to delete the last line from the file without creating a new file, you could do something like this:

RandomAccessFile f = new RandomAccessFile(fileName, "rw");
long length = f.length() - 1;
do {
length -= 1;
f.seek(length);
byte b = f.readByte();
} while(b != 10);
f.setLength(length+1);
f.close();

Start off at the second last byte, looking for a linefeed character, and keep seeking backwards until you find one. Then truncate the file after that linefeed.

You start at the second last byte rather than the last in case the last character is a linefeed (i.e. the end of the last line).



Related Topics



Leave a reply



Submit