0

I would like to add the path instead of the file name in BufferedReader? I want to use the path because I want the code to pickup any file that has the name "audit" in that specific folder.

So I am currently using this method below, but it only works when I add the absolute path.

`

public static void main(String[] args)
        throws IOException {
    List<String> stngFile = new ArrayList<String>();
    BufferedReader bfredr = new BufferedReader(new FileReader
            ("file path"));



    String text = bfredr.readLine();
    while (text != null) {
        stngFile.add(text);
        text = bfredr.readLine();
    }
    bfredr.close();
    String[] array = stngFile.toArray(new String[0]);

    Arrays.toString(array);
    for (String eachstring : array) {
         System.out.println(eachstring);
    }

}

`

I am new to programming any help is much appreciated. Thanks in advance.

1 Answers1

0

FileReader also has a constructor that takes a file. You can create a file object using a URI or a string for the path. You could use a FileFilter or just check if each file matches the name you provide, which is how i would do it:

To get all files in a folder you can use folder.listFiles().
You can then use file.getName().contains("audit") to check if the filename contains "audit".

Note that this is case sensitive, to ignore case you would just use file.getName().toLowerCase().contains("audit") (make sure the string you check here, in this case "audit", is always lower case).

As pointed out by g00se, you will also have to check if file is actually a file and not a directory using file.isFile()

Then in a loop you just read out to content of each file that matches the above condition seperately.

If you need the files in all the subfolders aswell, see this post.

Example:

public static void main(String[] args) throws IOException {
    File folder = new File("C:\\MyFolder"); // the folder containing all the files you are looking for
    for (File file : folder.listFiles()) { // loop through each file in that folder
        if (file.getName().contains("audit") && file.isFile()) { // check if it contains audit in its name
            // your previous code for reading out the file content
            BufferedReader bfredr = new BufferedReader(new FileReader(file));
            List<String> stngFile = new ArrayList<String>();
            String text = bfredr.readLine();
            while (text != null) {
                stngFile.add(text);
                text = bfredr.readLine();
            }
            bfredr.close();
            String[] array = stngFile.toArray(new String[0]);
            
            Arrays.toString(array);
            for (String eachstring : array) {
                 System.out.println(eachstring);
            }
        }
    }

}
Lahzey
  • 373
  • 5
  • 17