Solved

Reading a word from a file in a directory

Posted on 2010-09-07
17
259 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
Comment Utility
: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
Comment Utility
The code compiles.
0
 
LVL 3

Expert Comment

by:shaleesh
Comment Utility
Are the results as expected.
0
 
LVL 3

Expert Comment

by:shaleesh
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks. I tried your code msk_apk and i get the following:

java FindName <Name>

Any help is much appreciated.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 10

Assisted Solution

by:gordon_vt02
gordon_vt02 earned 62 total points
Comment Utility
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
Comment Utility
also change                your searchroot in the code and recompile the code
0
 

Author Comment

by:Smock
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Never mind...my dumb self did not name the files properly. Your code makes perfect sense...Thanks a lot.
0
 

Author Comment

by:Smock
Comment Utility
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
Comment Utility
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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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 learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

728 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now