Brainy Brainy - 5 months ago 23
Java Question

File contents getting deleted after reading it using FilerReader Java

Recently I am doing a code review, the code is like this:

File j = new File(aFile);
System.out.println(j.length());
BufferedReader fileReader = new BufferedReader(new FileReader(j));
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(aFile.getPath());
System.out.println(j.length());


I have two questions:


  1. Is
    j
    a duplicate of
    aFile
    , because I have seen other huge methods for copying files, like here.

  2. The first
    System.out.println()
    prints
    32
    and the second, after creating a file reader, prints
    0
    . So, why are the contents getting deleted? Could someone explain what's happening here?



I put those
System.out.println()
statements to check if the file is empty or not.

Solution:

After Reading through the answers, I think I found what's wrong with the code. If
j
is just a reference, then the
fileWriter
is trying to write into the same file and it is cyclic. Am I right here?

Answer Source

You're not showing us everything, are you?

The presented code definitely does not change or delete the file, as is already indicated by the names of the classes you are using: BufferedReader, FileReader (note Reader in both).

I thought there might be a slim chance that some operating systems would lock the file once you create the Readers, hence not even allowing a File object to read the length() property anymore. However, I couldn't find that documented or reported anywhere, so I highly doubt it.

I ran the following code, where test is a plain text file containing 0123456789 (length 10):

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class StackOverflow {
    public static void main(String[] args) {
        File f = new File("test");
        System.out.println("Length before: " + f.length());
        try {
            BufferedReader fileReader = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("Length after: " + f.length());
    }
}

Result:

Length before: 10
Length after: 10

Hence, I suspect the issue lies elsewhere.