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

    Default Why is my program still writing data i dont want

    Basically i have a program to read in the contents of a folder and capture instances of a substring stored between two strings. I want the instances of the substring called "resourceline" to be stored within an array and then sorted and printed into a new document.

    However i only want the instances to be stored IF they dont already exist and if the string does not contain certain symbols. I am doing this because i get too much irrelevant data come accross.
    The problem is the progam is working but still writing data that i dont want.

    please help
    regards S

    my code is below

    Java Code:
     
      
     /** Imported Java Libraries */
    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 find the value between the beginning and end of a string*/  
        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:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\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();
    						    boolean checkContains1=resourceline.contains("$");
    							boolean checkContains2=resourceline.contains("=");
    							boolean checkContains3=resourceline.contains("\>");
    							boolean checkContains4=resourceline.contains(":");
    							boolean checkContains4=resourceline.contains(".");
    							if (checkContains1 || checkContains2 || checkContains3 || checkContains4 || checkContains5)
    							{
    								  
    							}
    							if (arrayList.contains(resourceline)){
    								  
    							}
    						
    						    else{      
                                     arrayList.add(resourceline);   
      
                                    }
    						}								
      
    					}  
                        System.out.println("/**This Is A List Of Includes Within The Component*/");					
                        sortAndPrint(arrayList);
                        System.out.println("/*******This Is The End Of The list Of Includes*******/");					
                        writeResults(arrayList, "C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\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 f = new Find("myDir", "<\\$", "=", "C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\Test\\filetest.txt");   
    	}   
    	 
    	 
    	 
    	}

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Ok, this is not your first thread, so you should know this by now. What do you get? What do you expect?
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    BTW: Your code won't even compile, so I'm surprised that you get an output at all.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  4. #4
    Prajin's Avatar
    Prajin is offline Senior Member
    Join Date
    Jun 2010
    Location
    Ktm, Nepal
    Posts
    120
    Rep Power
    0

    Default

    No, OP code did compile in mine after I removed some errors.
    I created a .txt file with a word including symbols >,:, $ etc.
    The result is whenever program is run it creates new blank file, overwriting old ones.That's not what is wanted.
    -

  5. #5
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    That's what code tends to do, remove errors and then it compiles :rolleyes:

    How do you know what is wanted? The OP posted uncompilable code, maybe the right version of the code does something completely different and doesn't have blurbs like empty if statement blocks.
    My crystal ball is in service at the moment.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    My code compiles, ive been making several editations today so apologies if it didnt at first.

    The program itself does compile, it reads in a folder of items capturing a substring value between two strings.

    Once the string value is captured it is stored in an array.
    However (this is the adaptation to the original) instead of looking for resource names which are individual and occur once. I am now looking to extract idoc variables, which have many of the same instances and can be contained in many files.

    This presents a problem as I only want a single instance list of each variable used. The idea is to check if the string value already exists or contains any of the symbols. If it does then it gets dumped and loops to read the next line. Otherwise it stores the value in the arrayList.

    At the end of the arrayList the output is written to a new file.
    The problem is the output is not removing the values containing the symbol exceptions as expected, im still getting alot of irrelevant data come through.

    For example instead of removing values containing $whatthehellisthisdoinginhere$/morerubbishhere... they are still appearing

    regards S
    Last edited by SwissR; 07-27-2010 at 06:28 PM.

  7. #7
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Ok, fine. Now post the compilable, runnable code as it is now.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    Apologies if the formatting is a bit lame, the forum doesn't seem to get on well with copying and pasting from NOTEPAD++ sometimes.

    regards S


    Java Code:
     
      
     /** Imported Java Libraries */
    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 find the value between the beginning and end of a string*/  
        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:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\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();
    						    boolean checkContains1=resourceline.contains("$");
    							boolean checkContains2=resourceline.contains("=");
    							boolean checkContains3=resourceline.contains(">");
    							boolean checkContains4=resourceline.contains(":");
    							if (checkContains1 || checkContains2 || checkContains3 || checkContains4)
    							{
    								  
    							}
    							if (arrayList.contains(resourceline)){
    								  
    							}
    						
    						    else{      
                                     arrayList.add(resourceline);   
      
                                    }
    						}								
      
    					}  
                        System.out.println("/**This Is A List Of Includes Within The Component*/");					
                        sortAndPrint(arrayList);
                        System.out.println("/*******This Is The End Of The list Of Includes*******/");					
                        writeResults(arrayList, "C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\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 f = new Find("myDir", "<\\$", "=", "C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\Test\\filetest.txt");   
    	}   
    	 
    	 
    	 
    	}

  9. #9
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Well you never do anyting if the line contains special characters:
    Java Code:
    if (checkContains1 || checkContains2 || checkContains3 || checkContains4)
    {
    								  
    }
    And you could avoid the duplicates by using a Set instead of the List.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    Quote Originally Posted by SwissR View Post
    Apologies if the formatting is a bit lame, the forum doesn't seem to get on well with copying and pasting from NOTEPAD++ sometimes.
    I think it's down to tabs. You shouldn't use tabs for indentation since different systems can have different tab settings. The coding standards recommend spaces.

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

    Default

    But isn't that the point? If the string contains any of the special characters or already exists in the array then do nothing with the string. I.e. dump it.
    Otherwise we add the string to the arrayList???

    regards S

  12. #12
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Uhm no, you never dump anything, you just do nothing and still add it later.
    What you intend to do is this
    Java Code:
    if (!(checkContains1 || checkContains2 || checkContains3
    	|| checkContains4) && !arrayList.contains(resourceline)) {
    	arrayList.add(resourceline);
    }
    Last edited by PhHein; 07-28-2010 at 11:07 AM.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    Oh i've been reading it as though I only add the string if it doesn't contain those characters or already exist, and then continue the loop to the next line.

    If thats the case then what should I do to not add the value, set resourceline to null?

    regards S

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

    Default

    Hi PhHein,

    I've literally just tried it two ways and come back to resolve the post.I didnt actually realise you posted a solution before as it didnt come up.

    Your way was one approach but I also noticed that I was using two seperate IFS and realised that I should be using an else if.

    Anyway both solutions work the same. Thank you for your post.

    Seems like theres a lot of regulars on here like yourself, tolls, norm etc. Do u guys help run the site???

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,775
    Blog Entries
    7
    Rep Power
    21

    Default

    I recognize that code; the 'find' method is mine; I supplied it in an awfully long thread that would never end ... I could be mistaken but I don't think so; that other thread started off as 'dynamic html' but turned out to be similar to this thread ...

    kind regards,

    Jos

  16. #16
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Quote Originally Posted by SwissR View Post
    Seems like theres a lot of regulars on here like yourself, tolls, norm etc. Do u guys help run the site???
    Nope. :cool:
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    Someone runs this place??
    ;)

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

    Default

    Lol ok, just wondering thats all. I seem to see you guys popping up in posts all over the place and thought you might work on here.

    As for the Find method, i think when i joined up i was lucky enough to come accross something to start me off. It was kind of along the lines of what I wanted to do, just a bit smaller scale.

    My programs working now but im getting a little annoyed with this character search.

    in my If checkContains... statement how do i include the check for my resource line length.

    for example I've looke into the string api and found an example.
    Now i certainly dont need a new class and can initiate the int counter at the top of the find method and intend to call the for loop below just under my trimming of the resourceline. This should count the value length before doing any of the checking.

    My question is how do i put it so that I can say if my resourceline length is 1||2 characters within the IF i already has.

    The example below showshow to check a predefined string and then use + count + to output the count value into the string. But i dont want that

    Any ideas java guru's :)

    Java Code:
    public class Main {
        
        /**
         * This method counts the number of letters in a String
         */
        public void countLetters(String str) {
            
            if (str == null)
                return;
            
            int counter = 0;
            
            for (int i = 0; i < str.length(); i++) {
    
                if (Character.isLetter(str.charAt(i)))
                    counter++;
            }
            
            System.out.println("The input parameter contained " + counter + " letters.");
        }
    
        
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new Main().countLetters("abcde123");
        }
    }

  19. #19
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    What? I have no idea what you are trying to do. But your counter is complicated:
    Java Code:
    int counter = str.replaceAll("[^a-zA-Z]", "").length();
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

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

    Default

    It's complicated possibly in terms of lines of code, but it's a pretty basic "walk through a string" as far as a solution goes. It's understandable in terms of "I'm counting here!"

    Someone who doesn't know regex would find the single line you have to be akin to some arcane formula...:)

Page 1 of 2 12 LastLast

Similar Threads

  1. Writing the data into RandomAccessFile
    By vasavi.singh in forum New To Java
    Replies: 5
    Last Post: 01-31-2013, 08:12 AM
  2. Replies: 3
    Last Post: 07-28-2010, 03:49 PM
  3. Dont use this program, Im warning you!
    By Addez in forum JCreator
    Replies: 3
    Last Post: 11-28-2009, 08:18 PM
  4. Data Files - A problem that I dont understand :D
    By Exhonour in forum New To Java
    Replies: 7
    Last Post: 01-20-2009, 06:13 AM
  5. Writing Data or Objects?
    By Goodwine in forum New To Java
    Replies: 2
    Last Post: 11-26-2008, 01:36 AM

Posting Permissions

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