-2

I am writing new files into a directory on daily basis.

BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\difftest\\newfiles\\"+decisionList.get(i)+"_"+i+".txt"));

Before creating new files, I want to delete the previously added files existing in the folder. And the previous files will not override with new ones because the file names are different. How can I achieve this?

Richa Sharma
  • 75
  • 1
  • 9

2 Answers2

0

The following code can be helpful.

(This is just the idea of what you can do and I'm not sure about bugs.)

public class rename 
{ 
    public static void main(String[] argv) throws IOException 
    { 
         // Path of folder where files are located 
         String folder_path = 
           "C:\\Users\\Anannya Uberoi\\Desktop\\myfolder"; 

         // creating new folder 
         File myfolder = new File(folder_path); 

         File[] file_array = myfolder.listFiles(); 
         for (int i = 0; i < file_array.length; i++) 
         { 

            if (file_array[i].isFile()) 
            { 

                File myfile = new File(folder_path + 
                     "\\" + file_array[i].getName()); 
                myfile.delete(); 
            } 
        } 
    } 
} 
Mark
  • 5,089
  • 2
  • 20
  • 31
Hamid Ghasemi
  • 880
  • 3
  • 13
  • 32
0

You can delete all existing files from the given directory using this one liner code,

Arrays.asList(new File("C:\\difftest\\newfiles").listFiles()).stream().forEach(File::delete);

So, just place this line of code before your BufferedWriter line, like this,

Arrays.asList(new File("C:\\difftest\\newfiles").listFiles()).stream().forEach(File::delete);
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\difftest\\newfiles\\"+decisionList.get(i)+"_"+i+".txt"));
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36