Jason arora
Jason arora

Reputation: 550

How to read data from more than 1 text files using regular Expression in java?

Given more than one files in a directory

I have to read only the text files from a directory and print all the information inside it.

My Implementation:

File filepath=new File("c:/test");
Pattern p=Pattern.compile("[a-zA-Z0-9_]+.txt");
String s1[]=filepath.list();
for (int i=0;i<s1.length;i++){
 Matcher m=p.matcher(s1[i]);
 if(m.find()&&m.equals(s1));
 System.out.println(s1[i]);
 File file1=new File(s1[i]);
 readFromFile(file1);       
 }

 static void readFromFile(File filename) throws IOException{
 String line = null;    
 FileReader fileReader = new FileReader(filename); //1

 BufferedReader bufferedReader = new BufferedReader(fileReader);
 while((line = bufferedReader.readLine()) != null) {
 System.out.println(line);
    }   
    bufferedReader.close();
    fileReader.close();

}
  1. While running the above program i am getting NullPointer at position 1 as indicated in the code.
  2. Though I know the approaches using fileList method in file class I can read all the files in a directory and I also know that i can use endsWith method in String classto read only text file.

But I wanted to know how using above implementation I can read all the data inside the text files.

Can anyone guide me on this how to correctly handle the above approach.

Upvotes: 0

Views: 178

Answers (1)

Alexander Farber
Alexander Farber

Reputation: 23018

You probably have a problem while reading the file.

To understand what problem exactly do you have - "file not found" or maybe "insufficient read permissions" - always catch and print the exception when opening files for reading or writing (and also for reading directories):

public static void main (String[] args) {
    readFromFile(new File("nonexistant.txt"));
}

public static void readFromFile(File file) {
    try (FileReader fileReader = new FileReader(file);
         BufferedReader bufferedReader = new BufferedReader(fileReader)) {
        for (String line = bufferedReader.readLine(); 
             line != null; 
             line = bufferedReader.readLine()) {

            System.out.println(line);
        }
    } catch (Exception ex) {
            System.err.print(ex);
    }
}

Here it prints the reason:

java.io.FileNotFoundException: nonexistant.txt (No such file or directory)

Once you have fixed this issue, move to the file parsing.

Upvotes: 1

Related Questions