Search code examples
javagenetic-algorithmfileoutputstreamfilewriter

Looping Main Method while Writing Output Data to TXT File


So, I am working on a java project that is concerned with genetic algorithm.

I have a main method that calls a function (Let's call it function 1) that calculates through until the specified iterations. I wanted to run the main method 100 times and collect the data, so I decided to use FileWriter inside the function 1 that I am calling in my main method.

    public static int Runcnt = 0;
    static int o = 0;
    public static File statText = new File("C:\\Users\\ShadyAF\\Desktop\\StatTest.txt");
    public static void main(String [] args){
    while(Runcnt <= 100)
    {
        final long startTime = System.nanoTime();
        MainAlgorithm mA = new MainAlgorithm("config.xml");
        mA.cMA();
        final long duration = System.nanoTime() - startTime;
        System.out.println(duration/1000000000 + " seconds");
        o = 0;
    }

The above snippet of code is the main that I'm trying to loop. (function 1)

    System.out.println("best = "+Main.indx+"   = "+Main.val);
    System.out.println("max_cnt: " + Main.max_cnt);

    try {
          FileOutputStream is = new FileOutputStream(Main.statText);
          OutputStreamWriter osw = new OutputStreamWriter(is);    
          Writer w = new BufferedWriter(osw);
          w.write("#" + Main.Runcnt + " Best#: " + Main.indx + " BestScore: " + Main.val + " MaxCnt: " + Main.max_cnt + "\n");
          w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to file.");
        }

The above snippet of code is the mA.cMa() function that is inside the main loop.

I ran the code for a while and it appears that the program writes to the file only for the first loop and does not do anything for the rest of the looops.

Any help is much appreciated!

Edit: Why am I getting downvoted? At least leave a helpful comment :/


Solution

  • You should change your pattern from scratch... anyway you can try with something like this in your Main:

    public static Path pathFile = Paths.get("C:\\Users\\..blah..\\stats.txt");
    

    Then use in your loop

    try {
        String log = "#" + Main.Runcnt + " Best#: " + Main.indx + " BestScore: " + Main.val + " MaxCnt: " + Main.max_cnt + "\n";
        Files.write(Main.pathFile, log.getBytes(), Files.exists(Main.pathFile) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
    } catch (IOException e) {
        // exception handling 
    }
    

    It is not so efficient, in particular in case of lot of records but whole code you wrote should need strong refactoring too :)