Reading a word from a file in a directory

Hello,

I've been working on this problem for a while now but to no avail. I have a directory which contains a bunch of folders which contain subfolders that contain a particular file. I'm trying to create a program that traverses the directory and searches for the particular file and then once it finds it, I want to read that file for a particular word. Once the word is found, I'm trying to put the word and the parentFile (the string name) in a table.

So to make this clearer,
I have a directory called root which contains a bunch of sub directories namely subdirectory a thru subdirectory z. A particular file called data.txt is contained in all the folders (a thru z). The word that i am trying to find is "John". That word is contained in file "data.txt" randomly in the different subfolders (a thru z). For instance, a could have the word but b does not. c has the word but f does not....e.t.c.

Once the word is found, I am trying to put the word- John as well as the parent file "a" in a table....
The last part is my biggest struggle. any help is much appreciated.

I promise to give points accordingly.

This is what i have so far...


import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class TraverseDirectory {

    private static void traverse(File dir) {
        if (!dir.exists()) System.out.println("Does not exist "+dir);

        if (dir.isDirectory()) {
            File[] children = dir.listFiles();
            for (int i=0; i<children.length; i++) {
                   traverse(children[i]);
            }
        } else if (dir.getName().equals("data.txt")) {
        	
        	else{
        		String regex = File.separator;
        		if("\\".equals(regex)) {
        			regex = "\\\\";
        			String[] subs = dir.getAbsolutePath().split(regex);
            		
            		//System.out.println(info);
        		}
        		
        		
        		String s1 = dir.getName();
        		String s2 = dir.getParentFile().getName();
        		


        	}
        } else {
            //System.out.println("Skipping "+dir);
        }
     }
    
 
    public static void main(String[] args) {
        traverse(new File("//roots/dir"));
    }
}

Open in new window

SmockAsked:
Who is Participating?
 
shaleeshConnect With a Mentor Commented:
Apologies for the delay. You just have to change the 28th,42nd and 52nd line

From :

28 : String s1 = dir.getName();
42 :sb.append(reader.readLine());
52 :x=fileText.indexOf(searchText));

To :

28 : String s1 = dir.toString();
42 : sb.append(line);
52 :x=fileText.indexOf(searchText);

in the code which I had provided previously. Anyway this was just to inform the mistakes which i made in code, but apparently msk_apk's code is much more user friendly than mine.

0
 
shaleeshConnect With a Mentor Commented:
:Could you check if this code compiles and works as expected.
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class TraverseDirectory {

    private static void traverse(File dir)
                {
        if (!dir.exists()) System.out.println("Does not exist "+dir);

        if (dir.isDirectory())
                        {
                        File[] children = dir.listFiles();
                        for (int i=0; i<children.length; i++)
                                {
                                traverse(children[i]);
                                }
                        } else if (dir.getName().matches("data.txt"))
                        {
                                                        System.out.println("I am inside else");
                        String regex = File.separator;
                        if("\\".equals(regex))
                               {
                               regex = "\\\\";
                               String[] subs = dir.getAbsolutePath().split(regex);
                               }
                        String s1 = dir.getName();
                        String s2 = dir.getParentFile().getName();
                        System.out.println(s1);
                        System.out.println(s2);


                        }
                 }


    public static void main(String[] args) {
        traverse(new File("//roots/dir"));
    }
}

Open in new window

0
 
SmockAuthor Commented:
The code compiles.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
shaleeshCommented:
Are the results as expected.
0
 
shaleeshCommented:
If you are looking for piece of code to search a string inside a file. Try the below code:

import java.io.*
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class TraverseDirectory {

    private static void traverse(File dir)
                {
	        if (!dir.exists()) System.out.println("Does not exist "+dir);

	        if (dir.isDirectory())
                        {
                        File[] children = dir.listFiles();
                        for (int i=0; i<children.length; i++)
                                {
				traverse(children[i]);
                                }
                        } else if (dir.getName().matches("data.txt"))
                        {
                        
                        String regex = File.separator;
                        if("\\".equals(regex))
                               {
				regex = "\\\\";
				String[] subs = dir.getAbsolutePath().split(regex);
                               }
                        String s1 = dir.getName();
                        String s2 = dir.getParentFile().getName();
			String searchText = "John"; 
			String line;
			int x=0;
			StringBuilder sb = new StringBuilder();

			try 	{
				BufferedReader reader = new BufferedReader(new FileReader(s1));
				//Reads until the end-of-file met

				while( null != ( line = reader.readLine() ) ) 
					{
					//Read line-by-line directly
					sb.append(reader.readLine());
					}

				}
			catch(IOException ex) {
				ex.printStackTrace();
				}

			String fileText = sb.toString();

			x=fileText.indexOf(searchText));

			if(x >= 0)
				{
				//If string is found
				System.out.println(s1);
				System.out.println(s2);
				}


                        }
                 }


    public static void main(String[] args) {
        traverse(new File("//roots/dir"));
    }

}

Open in new window

0
 
SmockAuthor Commented:
With the code that you gave me, I now get an error message saying that "the system cannot read the file". I didn't do anything differently.

thanks.
0
 
objectsConnect With a Mentor Commented:
first recurse the directory, when you find the file you need to read the words from the file to find the one you're after
0
 
msk_apkConnect With a Mentor Commented:
Attached is the code that does the required functionality
import java.io.*;
import java.util.jar.*;
import java.util.*;

public class FindName
{
	private String name = "John";
	private String searchRoot = "E:\\text\\folder";
	//private String searchRoot =".";
	private NameFilter filter = null;
	private HashMap nameMap = null;
	
	public FindName(String name)
	{
		try
		{
			if(name != null)
			{
				this.name=name;
			}
			nameMap = new HashMap();
			filter = new NameFilter();
			search(new File[]{new File(searchRoot)});
			System.out.println(nameMap);	
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
	}
	
	private void search(File[] files)
	{
		try
		{
			for(int i=0;i<files.length;i++)
			{
				File file = files[i];
				if(file.isDirectory())
				{
					search(file.listFiles(filter));
				}
				else
				{
					try
					{
						if(checkForNameEntry(file))
						{
							//String directoryName = file.getParentFile().getName();
							nameMap.put(name,file.getName());
						}
					}
					catch(Exception eee)
					{
						eee.printStackTrace();
						break;
					}
				}
			}
		}
		catch(Exception ee)
		{
			ee.printStackTrace();	
		}

	}
	
	private boolean checkForNameEntry(File file)
	{
		//System.out.println(file);
		BufferedReader reader = null;
		try
		{
			reader = new BufferedReader(new FileReader(file));
			String temp = null;
			
			while( (temp = reader.readLine()) != null)
			{
				if(temp.indexOf(name) > -1)
				{
					return true;
				}
			}
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
		finally
		{
			try
			{
				reader.close();
			}
			catch(Exception ee)
			{
				ee.printStackTrace();
			}
		}
		
		return false;
	}
	
	private class NameFilter implements FilenameFilter
	{
		public boolean accept(File dir, String name)
		{
			boolean result = false;
			File file = new File(dir.getAbsolutePath()+File.separator+name);
			//System.out.println(file);
			if(file.isDirectory() || name.endsWith(".txt"))
			{
				result = true;
			}
			return result;
		}
	}
	
	
	public static void main(String a[])
	{
		if(a.length != 1)
		{
			System.out.println( "java FindName <Name>");
			return;
		}
		FindName c = new FindName(a[0]);
	}
}

Open in new window

0
 
SmockAuthor Commented:
Thanks. I tried your code msk_apk and i get the following:

java FindName <Name>

Any help is much appreciated.
0
 
gordon_vt02Connect With a Mentor Commented:
You need to run his code with the name you are looking for as an argument:

java FindName John
0
 
msk_apkCommented:
also change                your searchroot in the code and recompile the code
0
 
SmockAuthor Commented:
Thanks. i tried that and I'm getting no results. My console output is blank. Sorry for the trouble.
0
 
SmockAuthor Commented:
Thanks. I tried that. My problem is that I don't get any outcome. It's like it's searching forever. My actual file "data.txt" is embedded in a folder that has many super folders.

so it's like

root/folder1/folder2/folder3/data.txt.

Also, it is also embedded in root/folder1/folder2/folder4/data.txt

I don't know if that's a cause for the problem.
Please help
0
 
msk_apkConnect With a Mentor Commented:
try putting some print statements or uncomment some of the print statements in the code, then compile and rerun the code. are you running it in linux? if yes, then you need to give the searchRoot directory with the right syntax.
0
 
SmockAuthor Commented:
Never mind...my dumb self did not name the files properly. Your code makes perfect sense...Thanks a lot.
0
 
SmockAuthor Commented:
One more thing....
I have the following:

\\root\subdir1\folder1\folderA\subfolder_a\data.txt
\\root\subdir1\folder1\folderA\subfolder_b\data.txt
\\root\subdir1\folder1\folderA\subfolder_c\data.txt

Basically, I’m trying to modify the code such that if the actual word that I am looking for e.g. “John” is found in data.txt in each dir i.e. subfolder_a, subfolder_b and subfolder_c., I will print out something like John Is found in subfolder_c as subfolder_c is contained in folderA.

I hope this is not too confusing.

Thanks.
0
 
SmockAuthor Commented:
Thank you.
One more thing....
I have the following:

\\root\subdir1\folder1\folderA\subfolder_a\data.txt
\\root\subdir1\folder1\folderA\subfolder_b\data.txt
\\root\subdir1\folder1\folderA\subfolder_c\data.txt

Basically, I’m trying to modify the code such that if the actual word that I am looking for e.g. “John” is found in data.txt in each dir i.e. subfolder_a, subfolder_b and subfolder_c., I will print out something like John Is found in subfolder_c as subfolder_c is contained in folderA.

I hope this is not too confusing.

Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.