0

I have been doing the following for a project and could not find the problem with it. I have been trying to find all the mp3 files available in my computer, the code works fine till the if condition if(extension == "mp3")

On debugging I found that the if condition does not execute even when the condition is true.

public class AudioService {

    File[] audioFiles;
    File[] roots = File.listRoots();
    ArrayList<AudioFile> audios = new ArrayList<AudioFile>();
        int idIterator = 0;

    public List<AudioFile> getLocalAudioFiles() {
        for (int i = 0; i < roots.length; i++) {
            searchDir(roots[i]);
        }
        return audios;
    }

    public void searchDir(File directory) {
        File[] filesList = directory.listFiles();
        for (int i = 0; i < filesList.length; i++) {
            AudioFile af = new AudioFile();
            if (filesList[i].isDirectory()) {
                searchDir(filesList[i]);
            } else {
                int dotLast = filesList[i].getName().lastIndexOf('.');
                String extension = filesList[i].getName().substring(dotLast+1);
                if(extension == "mp3") {
                    idIterator++;
                    af.id = idIterator;
                    af.name = filesList[i].getName();
                    af.path = filesList[i].getPath();
                    af.type = extension;
                    audios.add(af);
                }
            }
        }
    }

    public static void main(String args[]) {
        List<AudioFile> af;
        AudioService as = new AudioService();
        af = as.getLocalAudioFiles();
    }
}

I don't know where I went wrong, Need some help here. Thanks in Advance.

1 Answers1

2

String is not a primitive. You need a special check for equality like,

if( "mp3".equals(extension)) { }
Dark Knight
  • 8,218
  • 4
  • 39
  • 58
  • Thanks, It helped a lot. –  Jan 31 '18 at 03:29
  • @MadhanBalaji Please avoid comments like "Thanks" on forum. If you think solution is worth, simply upvote the answer and accept it by marking answer as correct. – Dark Knight Jan 31 '18 at 03:32