Remove last line I wrote using FileWriter, java

By : Gaussia
Source: Stackoverflow.com
Question!

(I've this kinda of issue several times, but finally decided to ask how to do it) My code is something like this (not really, but so you get the point):

FileWriter fW = new FileWriter(new File(fileName));
while (entries.hasNext()) {
    fW.write(entry.next());
    fW.write("\n");
end

I have a file writer in java and use it to write entries to a file. After each entry I skip to the next line (one line for each entry). I don't know initially how many entries there actually will be.

Now this gives me an additional line at the end of the file (but there is no entry to fill it in). Is there a (simple) way using file writer to delete that last line.

(In this case you could get a similar result by writing the first outside the while loop and then swap the order:

fW.write("\n");
fW.write(entry.next());

but if there was something like:

fW.deleteLast()

it would be simple and useful to know. I have not found something like that.)

By : Gaussia


Answers
You could do a minor change to your loop such that this:

while (entries.hasNext()) {
    fW.write(entry.next());
    fW.write("\n");
}

Becomes this:

while (entries.hasNext()) {
    fW.write(entry.next());
    if(entries.hasNext())
        fW.write("\n");
}

Alternatively:

while (entries.hasNext()) {
    fW.write(entry.next());
    fW.write("\n");
}

Becomes:

if(entries.hasNext()) 
        fW.write(entry.next());

while (entries.hasNext()) {
        fW.write("\n");
    fW.write(entry.next());
}
By : npinti


INstead of writing to a file write to a StringBuilder. Then once you are done just remove the last character from your StringBuilder and then write the contents into a file. Disadvantage is if your content is too big (100s of Megabytes) then there is a memory usage issue.



This video can help you solving your question :)
By: admin