0

How to pass all files inside a folder as an input to a function?

lets say I have an folder called A and inside this folder I have three files as 1.txt, 2.txt and 3.txt.

On the other hand I have a function which gets a file name as input. How can I say run this function with all of the files inside folder A as your input.

if the function is

void readfile(String x)

I want to call readfile("1.txt"), readfile("2.txt") and readfile("3.txt").

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ali_IT
  • 7,551
  • 8
  • 28
  • 44
  • 1
    Did you try anything yourself? – WeMakeSoftware May 26 '13 at 07:50
  • 3
    Loop over the files in the directory. See ["\[java\] list directory"](http://stackoverflow.com/search?q=%5Bjava%5D+list+directory) for many related questions/examples like ["Best way to iterate through a directory in java?"](http://stackoverflow.com/questions/3154488/best-way-to-iterate-through-a-directory-in-java) – user2246674 May 26 '13 at 07:50

1 Answers1

1

You can get all the files from a directory as follows

File mainFolder = new File("C:\\yourDir");
getFiles(mainFolder);

public void getFiles(File f)
{
   File files[];
   if(f.isFile())
   System.out.println(f.getAbsolutePath());
   else
   {
      files = f.listFiles();
      for (int i = 0; i < files.length; i++) 
      {
         getFiles(files[i]);
      }
  }
}

This code just prints the files. You can store it a Set<String> and then give it to your function. To read from different files you will need to create that many FileReaders. For example

BufferedReader reader1 = new BufferedReader(new FileReader(new File("file1.txt")));
BufferedReader reader2 = new BufferedReader(new FileReader(new File("file2.txt")));
BufferedReader reader2 = new BufferedReader(new FileReader(new File("file3.txt")));

If you wish to each line from all 3 files at a time I suugest you create an infinite for loop and check if(reader1.readLine()!=null) for each reader. You can break; when all all readers return null. Do not forget to close the streams in finally block.

reader1.close();
reader1.close();
reader1.close();
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289