0

im trying to add counter in loop to a variable so the variable name changes during the loop as i am writing to a file so all the files has to be assigned a different variable name.

String[] pathnames;
        String tomcatUserFile="";
        String contextFile="";
        //Path tomcatConfDir=Paths.get(prop.getProperty("testClasspath"));
                File f = new File(prop.getProperty("tomcatZip"));
     pathnames=f.list();
int c=0;
            for (String i : pathnames) {    
                c++;
                tomcatUserFile = prop.getProperty("tomcatZip")+i+"/conf/tomcat-users.xml";
                Path tomcatUser= Paths.get(tomcatUserFile);
                contextFile = prop.getProperty("tomcatZip")+i+"/conf/context.xml";
                Path tomcatContext= Paths.get(contextFile);     
                    
                String tomcatUserFileContent+i = new String(Files.readAllBytes(tomcatUser),StandardCharsets.UTF_8);
                
                    log.info(prop.getProperty("SUCCESS"));
                }
                Files.write(tomcatUser,tomcatUserFileContent+i.getBytes());

i added +i to my variable tomcatUserFileContent so it changes the variable name every loop eg :tomcatUserFileContent0,tomcatUserFileContent1 etc but its not working. Any help?

  • You can't dynamically _create_ or _change_ a variable name in Java. What you probably want is to store the values in a `Map`, using as keys the "variable names" that you intended to use. Or just use an array or `ArrayList` and access the values by index. – Óscar López Jun 11 '21 at 13:34
  • 1
    @ÓscarLópez can u show an example with the above – Davertonator Jun 11 '21 at 13:35
  • `for (String i : pathnames)` can't do nothing since `pathnames` is never assigned – fantaghirocco Jun 11 '21 at 13:39
  • I've provided a link above your question, and closed it. You just want to generate dynamic strings, _not variables_. Move the `+ i + ...` part inside the getProperty call. – Óscar López Jun 11 '21 at 13:40
  • @ÓscarLópez i dont want to put it in getProperty() call..im trying to change that variable name only – Davertonator Jun 11 '21 at 13:42
  • @fantaghirocco updated... the loop is working but my loop counter adding to the string is not working – Davertonator Jun 11 '21 at 13:44
  • This will never, ever work: `String tomcatUserFileContent+i`. Use an array of strings, or a map. – Óscar López Jun 11 '21 at 13:45
  • 1
    @ÓscarLópez can u show example with my question..not the link u provided which is confusing – Davertonator Jun 11 '21 at 13:49

0 Answers0