Java - Delete Line from Text File by Overwriting While Reading It

Java - delete line from text file by overwriting while reading it

As others have pointed out, you might be better off using a temporary file, if there's a slightest risk that your program crashes mid way:

public static void removeNthLine(String f, int toRemove) throws IOException {

File tmp = File.createTempFile("tmp", "");

BufferedReader br = new BufferedReader(new FileReader(f));
BufferedWriter bw = new BufferedWriter(new FileWriter(tmp));

for (int i = 0; i < toRemove; i++)
bw.write(String.format("%s%n", br.readLine()));

br.readLine();

String l;
while (null != (l = br.readLine()))
bw.write(String.format("%s%n", l));

br.close();
bw.close();

File oldFile = new File(f);
if (oldFile.delete())
tmp.renameTo(oldFile);

}

(Beware of the sloppy treatment of encodings, new-line characters and exception handling.)


However, I don't like answering questions with "I won't tell you how, because you shouldn't do it anyway.". (In some other situation for instance, you may be working with a file that's larger than half your hard drive!) So here goes:

You need to use a RandomAccessFile instead. Using this class you can both read and write to the file using the same object:

public static void removeNthLine(String f, int toRemove) throws IOException {
RandomAccessFile raf = new RandomAccessFile(f, "rw");

// Leave the n first lines unchanged.
for (int i = 0; i < toRemove; i++)
raf.readLine();

// Shift remaining lines upwards.
long writePos = raf.getFilePointer();
raf.readLine();
long readPos = raf.getFilePointer();

byte[] buf = new byte[1024];
int n;
while (-1 != (n = raf.read(buf))) {
raf.seek(writePos);
raf.write(buf, 0, n);
readPos += n;
writePos += n;
raf.seek(readPos);
}

raf.setLength(writePos);
raf.close();
}

Java Delete a line from txt after reding the file

You will need a book class, like this:

public class Book {
private int series;
private String name;
private int intA;
private int intB;

public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}

When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.

Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.

To read your file into this array of objects, you can do this:

public static ArrayList<Book> readbooklist() {

ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");

try {
Scanner scnr = new Scanner(file);

while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("\t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}

scnr.close();

} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}

return booklist;
}

Remember to import proper dependency at the beginning of your class. Wish it helps!

Delete a line from a text file by overwriting using arrays to store the lines of a text file

Here is one way though better is to write to another file as you read from this, have a try -catch and close the file handles in the finally, use logging ...

package files;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;//growing array

class ReadFileRemoveLines// class test is a bad name
{
public static void main(String[]args)throws IOException//need to follow the signature or cant start the program
{
FileReader f=new FileReader("g.txt");
BufferedReader in=new BufferedReader(f);

ArrayList<String> ar = new ArrayList<String>(5);//initial size if you expect so many lines or leave out the 5 ()
String text;int i=0;
while((text = in.readLine()) != null)//spaces between symbols help readability
{
//why not test test here
if(!text.equals("the da vinci code")){
ar.add(text);
}
///i++;
}
/*
i=0;
for(i=0;i<ar.length;i++)
{
if(ar[i].equals("the da vinci code"))
{
ar[i]=null;
break;
}
}*/
in.close();
PrintWriter p=new PrintWriter(new BufferedWriter(new FileWriter("g.txt")));
for(int j=0;j<ar.size();j++)
{
System.out.println(ar.get(j));

p.println(ar.get(j));//why are you printint of i loop is j
}

p.close();
}
}

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

Deleting exact match String from text file

If you are using Java 8, You can do something like below using java.nio package:

Path p = Paths.get("PATH-TO-FILE");
List<String> lines = Files.lines(p)
.map(str -> str.replaceFirst("STRING-TO-DELETE",""))
.filter(str -> !str.equals(""))
.collect(Collectors.toList());
Files.write(p, lines, StandardCharsets.UTF_8);

Replace first line of a text file in Java

A RandomAccessFile will do the trick, unless the length of the resulting line is different from the length of the original line.

If it turns out you are forced to perform a copy (where the first line is replaced and the rest of the data shall be copied as-is), I suggest using a BufferedReader and BufferedWriter. First use BufferedReader's readLine() to read the first line. Modify it and write it to the BufferedWriter. Then use a char[] array to perform a brute-force copy of the remainder of the file. This will be more efficient than doing the copy line by line. Let me know if you need details..

Another option is to perform the reading and writing inside the same file. It'll be a bit more complex though. :) Let me know if you need details on this as well..



Related Topics



Leave a reply



Submit