0

I am stuck up in a odd situation that is I am creating a file in a folder but I need to make sure that before the creation of a file if any file is there in the folder then it must be deleted only the current file which is process should be there.

since in my application every day a job runs which create the file in that folder so when ever presently job is running it should delete previous day file and no file should be there in afolder but the code that is shown below creates the file in that folder but the issue is that previous day file or if the job run multiple time on the same day also then those files are also thhere in the folder which should be deleted please advise how to achieve this..

File file = new File(FilePath + s); //path is c:\\abc folder & s is file name fgty.dat file         
if (file.exists()) {
  file.delete(); 
}
file.createNewFile();

Please advise

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
Soni Sahai
  • 13
  • 3
  • 2
    What is `FilePath`? A `String` or a `File`? By the way, variable names begin with a lower case letter in Java. – C.Champagne Aug 30 '13 at 15:02
  • @C.Champagne it is string, yeah will change also please advise how to achieve this – Soni Sahai Aug 30 '13 at 15:04
  • I suggest you start using Google first, and try to find a solution to your programming problems, rather than keep asking here for a complete solution. SO is a Q&A site, but first you have to try it yourself before asking questions. There are plenty of resources on the web to get your started with the basic stuff (how to create/delete files, how to create zip archives, etc.), and most of the examples found using Google are detailed enough to answer most of your questions. – Laf Aug 30 '13 at 16:21

4 Answers4

1

Without seeing more of your code, it sounds like you just need to empty the folder before opening a new file, since right now you're only deleting the file with the exact name that you're going to write. Use the list method of file objects.

File newFile = new File(FilePath + s);
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
    f.delete();
}
newFile.createNewFile();

Note that this won't work if your folder contains other non-empty directories; you'll need a more robust solution. But the code above will at least delete all the files in the folder (barring Exceptions obviously) before creating the new file.

If, as you mentioned in the comments, you only want to delete *.dat files, it's as simple as putting a check in before you delete anything.

for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
    if (f.getName().endsWith(".dat")) { // Only delete .dat files
        f.delete();
    }
}
Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
  • there is a seprate folder reserve for these files,please also advise for robust solution , I want to delete all the files with .dat extension – Soni Sahai Aug 30 '13 at 15:05
  • Should `FilePath.list()` be `newFile.list()` ? And If I read the question correclty it should be `File newFile = new File(FilePath);` since FilePath is the directory (base on the comment in the code of OP). – Marc-Andre Aug 30 '13 at 15:22
  • @Marc-Andre No, you want to `list` all the children of the parent directory, which (assuming I understand the OP's problem) is `FilePath`. And `newFile` is the new file to create, not the directory in which to create it. – Henry Keiter Aug 30 '13 at 16:03
  • @SoniSahai "compilation error" tell me nothing I can help you with. My guess is that `FilePath` isn't what you think it is, but because you haven't shown that part of your code, I can't tell. If you only want to delete `.dat` files, just add an `if` statement around the `f.delete()` call. `if (f.getName().endsWith(".dat")) { f.delete(); }` – Henry Keiter Aug 30 '13 at 16:06
  • But FilePath isn't a `File` it's a String. from a comment of the OP : it is string, yeah will change also please advise how to achieve this. I've misread your code (my bad sorry), so I guess you need to add another `File` variable base on `FilePath` – Marc-Andre Aug 30 '13 at 16:06
  • @Marc-Andre Yes, you are correct about that one; my apologies. Fixing it now. – Henry Keiter Aug 30 '13 at 16:08
  • @HenryKeiter No problem the question of the OP isn't that clear and his code has some "errors". – Marc-Andre Aug 30 '13 at 16:11
1

In your place I'd move the directory to a different name, say abc.OLD, recreate it and then create your file. If everything goes well, at the end you can remove the ols directory.

If different instances of your program could be running at the same time you need to implement some form of synchronization. A rather simplistic approach could be to check if the abc.OLD directory exists and abort execution if it does.

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55
0
File file = new File(FilePath+"test.txt");
File folder = new File(FilePath);
File[] listOfFiles = folder.listFiles();

for(int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
        listOfFiles[i].delete();
    }
}
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
Ragavan
  • 997
  • 7
  • 11
  • could you also please explain what is happening the above code in brief, Thanks in advance – Soni Sahai Aug 30 '13 at 15:41
  • You give the folder in which your files are created in FilePath. Then it takes all files and folders within it. It iterates through and check if it's a file. If it is a file it deletes. At last it creates a new file. – Ragavan Aug 30 '13 at 15:43
0

First I think you can have problems with the way you instanciate your Fileobject because if you don't have your path separator (\), you will try to create c:\abcfgty.dat instead of c:\abc\fgty.dat.

Use instead :

File file = new File(filePath, s);

Then you can delete the files ending by ".dat". As I understood, you don't need to delete sub directories. (Here is a link that tells you how. See also here)

for (File f : filePath.list()) { // For each file in the directory, delete it.
    if(f.isFile() && file.getName().toLowerCase().endsWith(".dat");){
        f.delete();
    }
}
try {
    file.createNewFile();
} catch (IOException ex) {
    //Please do something here, at leat ex.printStackTrace()
}

Note that we can use a FileFilter to select the files to delete.

EDIT

As it was suggested in other answers, it might be preferable to move or rename the existing files instead of deleting them directly.

Community
  • 1
  • 1
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
  • @C Champagne where is f is initialized please explain Thanks in advance – Soni Sahai Aug 30 '13 at 15:45
  • @SoniSahai I think you need to study Java a bit before going on. `FilePath.list()` returns an array of `File`, that represent the files and foldes present in your folder "filePath". f is just an element of this array. – C.Champagne Aug 30 '13 at 15:57
  • @SoniSahai Please have look at enhanced for loop at https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with – C.Champagne Aug 30 '13 at 15:57
  • @SoniSahai and also have a look at http://tutorials.jenkov.com/java-io/file.html to get the basics on `File` – C.Champagne Aug 30 '13 at 15:59