Solved

Reading a word from a file in a directory

Posted on 2010-09-07
17
275 Views
Last Modified: 2012-05-10
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

0
Comment
Question by:Smock
  • 8
  • 4
  • 3
  • +2
17 Comments
 
LVL 3

Assisted Solution

by:shaleesh
shaleesh earned 210 total points
ID: 33618529
: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
 

Author Comment

by:Smock
ID: 33618792
The code compiles.
0
 
LVL 3

Expert Comment

by:shaleesh
ID: 33618940
Are the results as expected.
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 3

Expert Comment

by:shaleesh
ID: 33619253
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
 

Author Comment

by:Smock
ID: 33620665
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
 
LVL 92

Assisted Solution

by:objects
objects earned 52 total points
ID: 33622941
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
 
LVL 4

Assisted Solution

by:msk_apk
msk_apk earned 176 total points
ID: 33625694
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
 

Author Comment

by:Smock
ID: 33626836
Thanks. I tried your code msk_apk and i get the following:

java FindName <Name>

Any help is much appreciated.
0
 
LVL 10

Assisted Solution

by:gordon_vt02
gordon_vt02 earned 62 total points
ID: 33626962
You need to run his code with the name you are looking for as an argument:

java FindName John
0
 
LVL 4

Expert Comment

by:msk_apk
ID: 33627735
also change                your searchroot in the code and recompile the code
0
 

Author Comment

by:Smock
ID: 33627941
Thanks. i tried that and I'm getting no results. My console output is blank. Sorry for the trouble.
0
 
LVL 3

Accepted Solution

by:
shaleesh earned 210 total points
ID: 33628598
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
 

Author Comment

by:Smock
ID: 33631824
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
 
LVL 4

Assisted Solution

by:msk_apk
msk_apk earned 176 total points
ID: 33633089
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
 

Author Comment

by:Smock
ID: 33639907
Never mind...my dumb self did not name the files properly. Your code makes perfect sense...Thanks a lot.
0
 

Author Comment

by:Smock
ID: 33642014
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
 

Author Closing Comment

by:Smock
ID: 33652184
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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This video teaches viewers about errors in exception handling.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question