Search code examples
javafilefile-iofile-listing

list all subfolders in a directory and written on to a text file


I need to list all subfolders in a directory and written on to text file.But when i coded only the last subfolder is only written on to the file.Please help.I am a beginner to Java.

public class Main {
//    private Object bufferedWriter;

    /**
     * Prints some data to a file using a BufferedWriter
     */
    public void writeToFile(String filename) {
         try
        {
        BufferedWriter bufferedWriter = null;
        bufferedWriter = new BufferedWriter(new FileWriter(filename));


        int i=1;
        File f=new File("D:/Moviezzz");
        File[] fi=f.listFiles();
        for(File fil:fi)
        {
            if(fil.isHidden())
            {
                System.out.print("");
            }    
            else if(fil.isDirectory()||fil.isFile())
            {
               int s=i++;

               String files = fil.getName();



            //Start writing to the output stream
            bufferedWriter.write(s+" "+fil);
            bufferedWriter.newLine();

           // bufferedWriter.write(s+" "+files);
            }

        }


            //Construct the BufferedWriter object


    } catch (FileNotFoundException ex) {
          ex.printStackTrace();
       }catch (IOException ex) {
           ex.printStackTrace();}

    }


    public static void main(String[] args) {
        new Main().writeToFile("d://my.txt");
    }
}  

Solution

  • Uptil you call flush() method of BufferWriter class it will not write your data to file.

    It is not necessary to flush() every time in a loop. But you can write it after your end of the loop.

    Main thing to put that yourObj.flush() is to keep your buffer memory clean. as after call of that flush() method, data will be release from memory and written to your file.