简体   繁体   中英

How to Write the output into txt file using FileWriter

This is my java code to find the locations of files inside the directory and write them into a txt file as the output ,but after compilation the contents are not writing into txt file. please give me some solution.

public void listFilesAndFilesSubDirectories(String directoryName)
{
    File directory = new File(directoryName);
    List<String> list=new ArrayList<String> ();
    //get all the files from a directory
    if(directory.exists()){
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                if(file.getName().endsWith(".c")==true || file.getName().endsWith(".h")==true){
                    // System.out.println(file.getAbsolutePath());
                    list.add(file.getAbsolutePath());
                }
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
            else break;
        }

        try{
            FileWriter fw=new FileWriter("C:/Users/Public/afreen/module.txt");
            BufferedWriter out = new BufferedWriter(fw);

            for(String str: list)
            {
                System.out.println(str);
                out.write(str);
            }
            out.flush();
            out.close();
        }
        catch(Exception  e)
        {
            System.out.println(e);
        }
        System.out.println("Success....");
    }
    else
    {
        System.out.println("The directory is not exist , please enter a valid path");
    }
}

The above code will take the input as the path for directory and finds the location of files which I want.But the locations are not able to write into txt file,I am not abel to find the actual reason ,please help me out to find the solution of it.

Each time your method gets called (recursively) creates a new list and add the directory name to it but that list is not the one you are printing from, try to use a shared resource.
for example use a global variable or etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM