Search code examples
javafilewriterbufferedwriter

Unable to write to file using BufferedWriter


I have this Method that Lists the Files in a Directory and I need to write the same to a file. Apparently my

System.out.println(); is able to list the files and their Sizes and the Dates they were Modified. But My bufferedWriter Does not write Anything in the File. Here is My Method;

 public void walk( String path, int limit ) throws IOException {

            File root = new File( path );
            File[] list = root.listFiles();
            File rep = new File("report.txt");
            SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss");
            if (list == null) return;
            long size;
            BufferedWriter bw = new BufferedWriter(new FileWriter(rep));
            for ( File f : list ) {
            size = f.length()/1000/1000;
                if ( f.isDirectory() ) {
                    walk( f.getAbsolutePath(), limit );
                }
                else {
                if(size >= limit){
                    System.out.println( "File:" + f.getAbsoluteFile() + " " + size  + "MB Last Modified Date: " + sdf.format(f.lastModified()));
                    bw.write("File:" + f.getAbsoluteFile() + " " + size  + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");

                    }
                }
            }
          bw.close();
        }

What Am I Missing? I need to write the Out to the File report.txt but the file is empty.


Solution

  • I think it's because you're trying to open multiple buffered writers to the same file when it's calling itself through recursion. Try creating your writer outside of this method and pass it in as a parameter.


    Example

    public void myCallingMethod() throws IOException{
        File rep = new File("report.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(rep));
        walk("my/path", 4, bw);
        bw.close();
    }