Page 1 of 2 12 LastLast
Results 1 to 20 of 27
  1. #1
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default Reading In A Folder

    Hi guys im new to Java I was just wondering if theres an easy way to read in the contents of a folder rather than just an invididual file. For example at the moment im using

    "C:/Documents and Settings/KierenMcDonald/Desktop/Coding/Java/Test/resource.htm"));

    I would have liked to have thought that by simply giving a folder reference instead of a file reference it would have read in the folders contents.
    However upon testing my java compiler had a spaz at me and went .......er .....No i dont fancy doing that.

    please can someone give me the correct code to pull the folder into my program.

    Thanks so much for your time.

    regards

    S

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    read in the contents of a folder
    What do you mean "contents of a folder"? A folder contains other folders and files.
    Would the contents be a list of what is in the folder? See the File class for methods to get a list of what is in the folder.

  3. #3
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    Basically this folder contains a list of files however I am currently using a buffered reader to read in an individual file

    br = new BufferedReader(
    new FileReader(
    "C:/Myfolder/file.html"));

    Now my program at the moment captures data from this file and prints it to a new document.

    However now i'm at a stage in the programs lifecycle where i need to expand it a little to allow it to read in the contents of all files within a folder.

    So im a little confused as to how to encorporate this into my program.

    for example I've researched the code for the folder reference, please excuse the bad formatting of the forum if there is any.

    But i dont know how to encorporate it into my code. Im very new to java so im a bit bamboozled by this. Im planning on documenting this for any future references to make life a little easier if I should happen to have to do this again.



    Java Code:
    File myDir = new File("C:/myDir");// your folder address   
    if( myDir.exists() && myDir.isDirectory())//check folder exists and have more files too {    
    File[] files = myDir.listFiles() //gettting file list   
    for(int i=0; i < files.length; i++){   
    System.out.println(files[i]);   
    }   
    }
    regards S

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Normal processing for lists is in a loop.
    If you have code to process a single item, put that code in the loop and give it the elements from the list one by one in place of where you had used a single item.

  5. #5
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    Ok so I've contstructed the file reader to read the files however im now getting an issue with my method. Here is the code below.

    For some reason it cannot find my constructor.

    regards S

    Java Code:
    /** main method to find the resource name calling */  
        public static void main(String[] args) throws IOException {
    		Find findResources = new Find();
    	}
    The error that I am getting says

    cannot find symbol
    symbol constructor Find()
    location= Find findResources = new Find();

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Where is the class Find defined?
    If it is in a separate file is the Find.class file on the classpath?

  7. #7
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    The find class is in the same file, it is the only class used for example see below

    Java Code:
    public class Find {   
      
        BufferedReader br = null;   
      
        /** method to read html file line by line and return string to tore in array */  
        public Find(String fileName, String begin, String end,String whereToWrite) throws java.io.IOException {   
            try {   
                /** read in file */  
                String resourceline = null;   
                ArrayList<String> arrayList = new ArrayList<String>();   
                File myDir = new File("C:Test/resources");   
                if (myDir.exists() && myDir.isDirectory()) {   
                    File[] files = myDir.listFiles();   
                    for (int i = 0; i < files.length; i++) {   
                        br = new BufferedReader(new FileReader(files[i]));   
                        while ((resourceline = br.readLine()) != null) {   
                            resourceline = find(begin, end, resourceline);   
                            if (resourceline != null) {   
                                resourceline = resourceline.trim();   
                                arrayList.add(resourceline);   
      
                            }   
      
                        }   
                        sortAndPrint(arrayList);   
                        writeResults(arrayList, "C:\\Test\\filetest.txt");   
                    }   
                } else {   
                    System.out.println("This is not a directory");   
                }   
      
                /**  
                 * declaring string identifiers for beginning and end of string  
                 * aswel as one other line string to store the data between  
                 */  
                /** while line is not equal to null then find 3 string values */  
            } catch (FileNotFoundException ex) {   
                ex.printStackTrace();   
            } finally {   
                br.close();   
            }   
        }

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Where is the constructor in the Find class that would be used by your code:
    = new Find();

    The only constructor shown in the Find class takes several arguments.

  9. #9
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    I was trying to make an object of the class in main. However my previous working version of the program with the main method now does not work.

    Thats why im a little confused, I have several other methods doing different bits in my code.
    For example below is my program.

    The only issue seems to be with the main method

    Java Code:
    import java.io.BufferedReader;   
    import java.io.File;   
    import java.io.FileNotFoundException;   
    import java.io.FileReader;   
    import java.io.IOException;   
    import java.util.ArrayList;   
    import java.util.regex.Matcher;   
    import java.util.regex.Pattern;   
    import java.util.Collections;   
    import java.util.List;   
    import java.io.PrintWriter;   
    import java.io.FileWriter;   
      
    /** class to find string */  
    public class Find {   
      
        BufferedReader br = null;   
      
        /** method to read html file line by line and return string to tore in array */  
        public Find(String fileName, String begin, String end,String whereToWrite) throws java.io.IOException {   
            try {   
                /** read in file */  
                String resourceline = null;   
                ArrayList<String> arrayList = new ArrayList<String>();   
                File myDir = new File("C:/Test/resources");   
                if (myDir.exists() && myDir.isDirectory()) {   
                    File[] files = myDir.listFiles();   
                    for (int i = 0; i < files.length; i++) {   
                        br = new BufferedReader(new FileReader(files[i]));   
                        while ((resourceline = br.readLine()) != null) {   
                            resourceline = find(begin, end, resourceline);   
                            if (resourceline != null) {   
                                resourceline = resourceline.trim();   
                                arrayList.add(resourceline);   
      
                            }   
      
                        }   
                        sortAndPrint(arrayList);   
                        writeResults(arrayList, "C:\\Test\\filetest.txt");   
                    }   
                } else {   
                    System.out.println("This is not a directory");   
                }   
      
                /**  
                 * declaring string identifiers for beginning and end of string  
                 * aswel as one other line string to store the data between  
                 */  
                /** while line is not equal to null then find 3 string values */  
            } catch (FileNotFoundException ex) {   
                ex.printStackTrace();   
            } finally {   
                br.close();   
            }   
        }   
      
        /** method to sort and print the array collection */  
        private void sortAndPrint(List<String> results) {   
            Collections.sort(results, String.CASE_INSENSITIVE_ORDER);   
            for (String resourceline : results) {   
                System.out.println(resourceline);   
            }   
        }   
      
        /** method to find the value between the beginning and end of a string  
         */  
        public String find(String beg, String end, String resourceline) {   
            /** match pattern to store string between strings and match to line */  
            Pattern p = Pattern.compile(beg + "(.*)" + end);   
            Matcher m = p.matcher(resourceline);   
            return m.find() ? resourceline.substring(m.start(1), m.end(1)) : null;   
        }   
      
        /** method to print the results of the array into a new document */  
        private void writeResults(ArrayList<String> arrayList, String filename) {   
            try {   
                PrintWriter writer = new PrintWriter(filename);   
      
                for (String resourceline : arrayList) {   
                    writer.println(resourceline);   
                }   
                System.err.println("Your Data Has Been Written To The File Successfully");   
                writer.close();   
            } catch (Exception e) {   
                System.out.println("can't create output file \"" + filename + "\"");   
                e.printStackTrace();   
            }   
        }   
      
        /** main method to find the resource name calling */  
        public static void main(String[] args) throws IOException {
    		Find findResources = new Find();
    	}
    }

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Why do you want to make a Find object in the main method?

    What do you want the program to do after the Find object is created?

    If you only want to create an object, add this empty constructor to the Find class:
    public Find(){} // an empty constructor
    This will solve the compile error you got above.

  11. #11
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    Basically I want the program to look at each file take each occurance of a resource and store it in an array and then sort and print that array into a new file.

    I want the program to loop until the last document so that all files are read and printed out into one new organised txt file.

    The previous arguement in the main worked however now It does not.

    regards Nick

    So im a little confused as to why the object main class is now causing a problem and what I need to do to rectify it.

    now when i run the code i get exception in thread "main"

    Java.lang.nosuchmethoderror "main"

    regards S
    Last edited by SwissR; 07-20-2010 at 05:36 PM.

  12. #12
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    I only have the one constructor object but now that ive changed the Find() constructor to

    public Find(String fileName, String begin, String end,String whereToWrite)" ... so you need to pass in the directory name(eg "C:/myDir"), beginning string (eg "<@dynamichtml" ), end string(eg "@>>), targer file name (eg "C:\\\\Test\\filetest.txt")

    So its not finding it.
    What would be the best way around this issue, im thinking to create a new method and call it in the main. Would that work best?

    regards S
    Last edited by SwissR; 07-20-2010 at 05:48 PM.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,044
    Rep Power
    20

    Default

    Your constructor in Find was defined as:
    Java Code:
    public Find(String fileName, String begin, String end,String whereToWrite) throws java.io.IOException {...}
    The one you were attempting to use in the main() method had no parameters. Consequently it couldn't find a sutable constructor, so failed to compile.

    Presumably you want to pass those parameters to the Find object, so do it...

    As for why it's giving you a new error now, we can't tell.

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    when i run the code i get exception
    Please copy and post here the FULL text of the error message.
    Also show the full command line you execute to get that error.

  15. #15
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    I've passed the parameters in the object the only one thats having a bit of a spaz about is the reference to where to write the file. Its not finding it, I've referenced in the normal manner as above i.e. "C:\\Test\\filetest.txt " but its telling me that its not a statement and that its expecting a semi colon in the path.????

    regards S

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,044
    Rep Power
    20

    Default

    See Norm's post...in other words, give us all the details instead of paraphrasing.

    Also show us the line it is failing on...we cannot see your code from here, or your errors.

  17. #17
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    The only thing I have just changed is the Find object in the main method referencing the string variables as previously mentioned and then listing its parameters.

    The 2 errors the compiler throws are
    not a statement:

    public Find(String fileName, String begin, String end,String whereToWrite) throws java.io.IOException {"myDir", "<@dynamichtml", "@>", "C:\\Test\\filetest.txt"}

    And also a semi colon ';' is for some reason being expected in the write path parameter

    I'm only using a simple javac Find.java command

    I've not changed anything

    regards S
    Last edited by SwissR; 07-20-2010 at 05:52 PM.

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,044
    Rep Power
    20

    Default

    Um, what on earth syntax is that?

    What are you trying to do, because that is not Java code?

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Is this the first java class you have tried to define?
    Have you studied how to define constructors and methods?

  20. #20
    SwissR is offline Member
    Join Date
    Jul 2010
    Posts
    39
    Rep Power
    0

    Default

    I used the javac command to compile the program

    I then referenced the constructor and its string parameters, whats wrong with that?
    Surely if i was referencing the java parameters incorrectly it would throw out errors for each entire reference as there are 3 other string parameter references preceding the filewrite parameter.

    Unfortunately i cant copy and paste from the compiler, here is pretty much what its saying when i initiate the javac command.

    Find.java 93 :not a statement:
    public Find(String fileName, String begin, String end,String whereToWrite) throws java.io.IOException {"myDir", "<@dynamichtml", "@>", "C:\\Test\\filetest.txt"}

    error points to s in Desktop

    Find.java 93: ';' expected

Page 1 of 2 12 LastLast

Similar Threads

  1. Lock a folder
    By nchouhan15@gmail.com in forum New To Java
    Replies: 4
    Last Post: 03-13-2012, 08:33 AM
  2. Reading a .txt i a folder - help
    By Mattedatten in forum New To Java
    Replies: 6
    Last Post: 01-13-2010, 01:49 AM
  3. bin and lib folder
    By sdkanhere in forum New To Java
    Replies: 1
    Last Post: 10-07-2009, 04:46 PM
  4. Replies: 5
    Last Post: 08-21-2009, 11:03 AM
  5. Replies: 15
    Last Post: 03-18-2009, 10:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •