title: Moving files from one directory to another, using Java
body: <p>I have problems with moving files in directories in Java. The problem is that I cannot understand why the program behaves the way it behaves. Below is a (slight) modification of my real program. </p>
  
  <p>I traverse directories of a directory. In each of these traversed directories
  there are text files, which I want to move into two subdirectories of the traversed directory. I create these two directories (<code>trainingData</code> and <code>testData</code>). I want 30 of the files to be moved into the <code>testData</code> directory and 60 of them in the <code>trainingData</code> directory. For this purpose I make two for loops. </p>
  
  <p>In the code below, I have put first the loop moving the files into <code>trainingData</code>. And the good news is that all these 60 files really are moved into <code>trainingData</code>. However, the second loop seems not to make anything - no file of any of these 30 remaining files is moved. These 30 files continue to stay in the original (traversed) directory.</p>
  
  <p>Moreover, something very strange is that when I exchange the two loops - put the one moving the 30 files on the first place, and the other one after it, then the 30 files are correctly moved into <code>testData</code>, however, 30 of the other 60 files are moved into the <code>trainingData</code> directory and the rest 30 files stay in the original (traversed) directory. </p>
  
  <p>The program still does not do what I want (only partly), however, what bothers me is that I don't understand why is this difference(??) when I exchange the places of the two loops. The code is identical, and should work the same, shouldn't it?</p>
  
  <p>Thanks for the time of looking into the code, and if necessary I am willing to provide more code and explanations.  </p>
  
  <pre><code>File[] reviews = null;
  for(File sortedRevDir : sortedRevDirs) {
       reviews = sortedRevDir.listFiles();
       int numFiles = 90;
       int numTwoThirds = 60;
       int numOneThirds = numFiles - numTwoThirds;     
  
       String trainingDir = sortedRevDir.getAbsolutePath() + "/trainingData";
       File trDir = new File(trainingDir);
       trDir.mkdir();
       String testDir = sortedRevDir.getAbsolutePath() + "/testData";
       File tsDir = new File(testDir);
       tsDir.mkdir();
  
       for(int i = 0; i &lt; numTwoThirds; i++) {
           File review = reviews[i];
           if(!review.isDirectory()) {
                File reviewCopied = new File(trDir + "/" + review.getName());
                review.renameTo(reviewCopied);
           } 
       }
       for(int j = 0; j &lt; numOneThird; j++) {
           File review = reviews[j];
           if(!review.isDirectory()) {
            File reviewCopied = new File(tsDir + "/" + review.getName());
            review.renameTo(reviewCopied);
           }
       }
   }
  </code></pre>