Results 1 to 6 of 6
  1. #1
    Cyrus is offline Member
    Join Date
    Mar 2014
    Posts
    18
    Rep Power
    0

    Default Everything in ArrayList written twice

    I am trying to read a file into an array list, change some things about it, and then write it to another file. Files are getting written with what was read repeating a second time. I've tested the read method by having it print everything which goes into the ArrayList object. I then did the same with the write method which seems to write everything twice, as if everything is in the ArrayList twice, but I'm not sure how this is possible, since the read clearly did everything only once. Perhaps the ArrayList isn't the best collection to use for this purpose.

    The read method:
    Java Code:
    private ArrayList<String> read(File in) {
    		String line;
    		ArrayList<String> data = new ArrayList<String>();
    		
    		try {
    			BufferedReader r = new BufferedReader(new FileReader(in));
    						
    			while ((line = r.readLine()) != null) {
    				data.add(line);
    				//System.out.println(line);
    			}
    			
    		 	r.close();
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		return data;
    	}
    The write method:
    Java Code:
    private void write(File out, ArrayList<String> data) throws IOException {
    		System.out.println("Writing file: " + out.toString());
    		
    		PrintWriter w;
    		try {
    			w = new PrintWriter(new FileWriter(out));
    			
    			for (int i = 0; i < data.size(); i++) {
    				w.println(data.get(i));
    				System.out.println(data.get(i));
    			}
    			
    			w.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    			throw new IOException(e);
    		}
    		
    		
    	}
    The replace method, which I am including because it is used by the caller:
    Java Code:
    private ArrayList<String> replace(ArrayList<String> data) {
    		ArrayList<String> out = new ArrayList<String>();
    		String line;
    		String elem;
    		String token;
    		Enumeration<String> e = repList.keys();
    		while (e.hasMoreElements()) {
    			elem = e.nextElement();
    			//System.out.println("replacing element " + elem);
    			token = elem.toUpperCase();
    			token = "%" + token + "%";				
    			for (int i = 0; i < data.size(); i++) {
    				line = data.get(i);
    				line.replace(token, repList.get(elem));
    				out.add(i, line);
    			}
    		}
    		
    		return out;
    	}
    The caller:
    Java Code:
    private void fpmGen(String user, String template) 
    					throws ExcGenNotmpl, Exception {
    		database.Templates t = new database.Templates();
    		write(new File(fpmPath + "/" + user + ".conf"), 
    				replace(read(new File(t.getfpmTemp(template)))));
    	}
    Last edited by JosAH; 03-01-2014 at 03:43 PM.

  2. #2
    Cyrus is offline Member
    Join Date
    Mar 2014
    Posts
    18
    Rep Power
    0

    Default Re: Everything is ArrayList written twice

    It would be good if a moderator could fix the grammar in the subject I've written is instead of in.

  3. #3
    Cyrus is offline Member
    Join Date
    Mar 2014
    Posts
    18
    Rep Power
    0

    Default Re: Everything is ArrayList written twice

    The ArrayList didn't work as I expected it would, and multiple entries could have the same index it seems. I've fixed the problem with thise code for the replace method. However, I consider the question still open for a recommendation of a better collection for storing files line by line.

    Java Code:
    private ArrayList<String> replace(ArrayList<String> data) {
    		boolean pastfirst = false;
    		ArrayList<String> out = new ArrayList<String>();
    		String line;
    		String elem;
    		String token;
    		Enumeration<String> e = repList.keys();
    		while (e.hasMoreElements()) {
    			elem = e.nextElement();
    			//System.out.println("replacing element " + elem);
    			token = elem.toUpperCase();
    			token = "%" + token + "%";				
    			for (int i = 0; i < data.size(); i++) {
    				line = data.get(i);
    				//System.out.println(i + ": " + line);
    				line.replace(token, repList.get(elem));
    				if (pastfirst) out.remove(i);
    				out.add(i, line);
    			}
    			pastfirst = true;
    		}
    		
    		return out;
    	}

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,602
    Rep Power
    5

    Default Re: Everything is ArrayList written twice

    Quote Originally Posted by Cyrus View Post
    The ArrayList didn't work as I expected it would, and multiple entries could have the same index it seems. I've fixed the problem with thise code for the replace method. However, I consider the question still open for a recommendation of a better collection for storing files line by line.
    First, you can edit your posts yourself (for about a day or so). ArrayList is just like an array only better. ArrayLists may not store multiple items per index. There must be something wrong with your code. It is unclear what file you are passing to your write method. I suggest you provide an Short, Self Contained, Correct Example that simply reads in lines of a file and stores them in an array list and prints them out. It should not be long and should show all of your code.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    Cyrus is offline Member
    Join Date
    Mar 2014
    Posts
    18
    Rep Power
    0

    Default Re: Everything in ArrayList written twice

    Here is my short self contained and correct example that demonstrates the problem.

    Java Code:
    import java.io.*;
    import java.util.Hashtable;
    import java.util.ArrayList;
    import java.util.Enumeration;
    
    class ReadReplWrite {
            private static Hashtable<String, String> repList = null;
    
            private static void write(File out, ArrayList<String> data) {
                    //System.out.println("Writing file: " + out.toString());
    
                    PrintWriter w;
                    try {
                            w = new PrintWriter(new FileWriter(out));
    
                            for (int i = 0; i < data.size(); i++) {
                                    w.println(data.get(i));
                                    //System.out.println(data.get(i));
                            }
    
                            w.close();
                    } catch (IOException e) {
                            e.printStackTrace();
                    }
    
    
            }
    
            private static ArrayList<String> replace(ArrayList<String> data) {
                    boolean pastfirst = false;
                    ArrayList<String> out = new ArrayList<String>();
                    String line;
                    String elem;
                    String token;
                    Enumeration<String> e = repList.keys();
                    while (e.hasMoreElements()) {
                            elem = e.nextElement();
                            token = elem.toUpperCase();
                            token = "%" + token + "%";
                            //System.out.println("replacing token " + token);
                            for (int i = 0; i < data.size(); i++) {
                                    line = data.get(i);
                                    //System.out.println(i + ": " + line);
                                    line = line.replaceAll(token, repList.get(elem));
                                    //System.out.println(token + "=" +  repList.get(elem));
                                    //if (pastfirst) out.remove(i);
                                    out.add(i, line);
                            }
                            pastfirst = true;
                    }
    
                    return out;
            }
    
            private static ArrayList<String> read(File in) {
                    String line;
                    ArrayList<String> data = new ArrayList<String>();
    
                    try {
                            BufferedReader r = new BufferedReader(new FileReader(in));
    
                            while ((line = r.readLine()) != null) {
                                    data.add(line);
                                    //System.out.println(line);
                            }
    
                            r.close();
                    } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
    
                    return data;
            }
    
            public static void main(String[] args) {
                    //Prepare the replacement strings.
                    repList = new Hashtable<String, String>();
                    repList.put("user", "cyrus");
                    repList.put("port", "9001");
                    repList.put("domain", "cyrutheg.org");
                    repList.put("directory", "/var/www/sites/cyrutheg");
    
                    //Use the methods.
                    write(new File("output.txt"),
                     replace(read(new File("input.txt"))));
            }
    }
    In the replace method, the for loop resets the index for every key it replaces. It then puts them the index location in the ArrayList. It should be replacing lines, but it seems to be starting new lines instead. So when I run the program the output is like this...

    Java Code:
    cyrus@debianvm:~/test$ cat input.txt 
    This is an example input.
    
    user %USER%
    port %PORT%
    directory %DIRECTORY%
    domain %DOMAIN%
    
    :-)
    cyrus@debianvm:~/test$ java ReadReplWrite 
    cyrus@debianvm:~/test$ cat output.txt 
    This is an example input.
    
    user %USER%
    port %PORT%
    directory %DIRECTORY%
    domain cyrutheg.org
    
    :-)
    This is an example input.
    
    user cyrus
    port %PORT%
    directory %DIRECTORY%
    domain %DOMAIN%
    
    :-)
    This is an example input.
    
    user %USER%
    port 9001
    directory %DIRECTORY%
    domain %DOMAIN%
    
    :-)
    This is an example input.
    
    user %USER%
    port %PORT%
    directory /var/www/sites/cyrutheg
    domain %DOMAIN%
    
    :-)
    The output is repeating, and that is problematic. If I changeabout the replace method above so that it deletes entries from prior iterations, this problem goes away. It seems like strange behavior for the ArrayList to need an index location deleted before I put things there.

    Java Code:
            private static ArrayList<String> replace(ArrayList<String> data) {
                    boolean pastfirst = false;
                    ArrayList<String> out = new ArrayList<String>();
                    String line;
                    String elem;
                    String token;
                    Enumeration<String> e = repList.keys();
                    while (e.hasMoreElements()) {
                            elem = e.nextElement();
                            token = elem.toUpperCase();
                            token = "%" + token + "%";
                            //System.out.println("replacing token " + token);
                            for (int i = 0; i < data.size(); i++) {
                                    line = data.get(i);
                                    //System.out.println(i + ": " + line);
                                    line = line.replaceAll(token, repList.get(elem));
                                    //System.out.println(token + "=" +  repList.get(elem));
                                    if (pastfirst) out.remove(i); //this line uncommented
                                    out.add(i, line);
                            }
                            pastfirst = true;
                    }
    
                    return out;
            }
    Now the output is fine...
    Java Code:
    cyrus@debianvm:~/test$ java ReadReplWrite
    cyrus@debianvm:~/test$ cat input.txt 
    This is an example input.
    
    user %USER%
    port %PORT%
    directory %DIRECTORY%
    domain %DOMAIN%
    
    :-)
    cyrus@debianvm:~/test$ cat output.txt 
    This is an example input.
    
    user %USER%
    port %PORT%
    directory %DIRECTORY%
    domain cyrutheg.org
    
    :-)
    The reason I needed a moderator is because I'm only allowed to edit posts, not the subject. I've made a mistake in the name of the subject.
    Last edited by Cyrus; 03-02-2014 at 09:23 AM.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,602
    Rep Power
    5

    Default Re: Everything in ArrayList written twice

    The problem is in your replace method. I assume the output should look like this.

    user cyrus
    port 9001
    directory /var/www/sites/cyrutheg
    domain cyrutheg.org

    First, you need to reverse the nesting of your enumeration and for loops. What you want to do is replace
    the current line with replacements for any possible key. So for each line, iterate thru all of the enumerations
    making replacements. Then, when done, add that line to the list. This addition should be done outside the
    enumeration loop (which is now the inner loop).

    Also, it may be too late but if you go to the advanced editor, I believe you can edit the title.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

Similar Threads

  1. New to Java need help. Have partial code written!!
    By therealvasile in forum New To Java
    Replies: 4
    Last Post: 07-11-2013, 08:43 PM
  2. Why this java code has written this way?
    By talenone in forum New To Java
    Replies: 7
    Last Post: 01-10-2013, 11:09 AM
  3. Are these well written algorithms?
    By dharav in forum New To Java
    Replies: 3
    Last Post: 01-12-2012, 08:27 AM
  4. Replies: 12
    Last Post: 07-07-2011, 08:49 PM
  5. Text file over written
    By bugger in forum New To Java
    Replies: 2
    Last Post: 11-11-2007, 07:32 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
  •