Search code examples
javaarraysfileooplocation

How to get all files from a certain folder with Java


I am trying to make a memory game with 16 cards in a Java Swing, I made a folder for all the images needed in a folder next to the java application itself:

(which is C:\Users\edwin\eclipse-workspace\A3 - Java\src\eindopdracht1\Plaatjes.java)

and the Images folder which contains 8 different Images:

C:\Users\edwin\eclipse-workspace\A3 - Java\src\eindopdracht1\Images

Now I want to put all 8 images twice in an array, using a for loop. For some reason Java doesn't recognize the second file above. Why is that? My code:

package eindopdracht1;

import java.io.*;

import javax.swing.*;

public class Plaatjes extends JButton {
    private File[] files = new File(
            System.getProperty("C:\\Users\\edwin\\eclipse-workspace\\A3 - Java\\src\\eindopdracht1\\Images"))
                    .listFiles();
    private File[] afbeeldingen = new File[16];

    public Plaatjes() {

        for (int i = 1; i < files.length * 2; i = i + 2) {
            afbeeldingen[i - 1] = files[i];
            afbeeldingen[i] = files[i];
            System.out.println(files[i]);
        }
    }
}

Solution

  • you should change this lines of code :

    private File[] files = new File(
                System.getProperty("C:\\Users\\edwin\\eclipse-workspace\\A3 -Java\\src\\eindopdracht1\\Images"))
               .listFiles();
    

    to

    private File[] files = new File("C:\\Users\\edwin\\eclipse-workspace\\A3 - Java\\src\\eindopdracht1\\Images").listFiles();