1

I am creating a dat file in C: drive folder named abc as shown below , Now my file is generated everyday now suppose if my file is generated today, then tommrow it will be also generated as usual but when tommrow it is generated I have to make sure that earlier day file is deleted as the space in that folder is limited and this check is every time need to be done previos day file to be get deleted from that folder , please advise how to achieve this..

File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc         //and filename through a method 


        if (!file.exists()) {
            file.createNewFile();
        }

FileOutputStream fileOutput = new FileOutputStream(
                file);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                fileOutput));
Nitesh Verma
  • 1,795
  • 4
  • 27
  • 46
Kishan Kumar
  • 21
  • 1
  • 1
  • 3
  • 3
    Just dont check that file exists or not. Write the content with same file name. It automatically replace the previous file. and if file doesn't exist then it will create one. – Vimal Bera Aug 22 '13 at 06:41

4 Answers4

7

why not use file.delete() ?

File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc         //and filename through a method 

if (file.exists()) {
     file.delete(); //you might want to check if delete was successfull
}
file.createNewFile();

FileOutputStream fileOutput = new FileOutputStream(file);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutput));
Alex
  • 409
  • 5
  • 12
2

If your file name same in time to time no need to delete that. By running your code tomorrow, will over write file created today.

Consider following case

    BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Test\test.txt"));
    bw.write("abbbb");
    bw.close();  // now this will create a test.txt in side Test folder

now run this by change writing String

    BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt"));
    bw.write("hihi");
    bw.close(); // now you can see file only containing hihi
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

You can change your code this way:

 if (file.exists()) {
      file.delete();
 }
 file.createNewFile();

And if it does not work, it's a matter of permission.

Saeed
  • 7,262
  • 14
  • 43
  • 63
0

If you are using Java 7 then there is standard way to get file creation time, So that you can check if file is created in previous day and should be delete.

    Path path = Paths.get("/filepath/");
    BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
    System.out.println("creationTime:"+ fileAttributes.creationTime());
Ashwani
  • 3,463
  • 1
  • 24
  • 31