I have a simple program that reads all the files from a given directory into an array. The array is then looped through and the file names listed in a JFrame as individual JLabels.

I am also able to read the file extension using this code:

                String extension = "";
                int i = FileName.lastIndexOf('.');
                if (i > 0) {
                    extension = FileName.substring(i+1);
                }

This works fine, however when I try to use the extension in an if statement like this:

                    if(extension == "java")
                     {
                        System.out.println(FileName);
                     } 
                    else
                    {
                      System.out.println("error");
                    }

all i get is error statements in the console, even though there are several java files in the directory (as can be seen in the results JFrame!)

Can anyone tell me what the problem is? Thanks!

有帮助吗?

解决方案

Change to this:

if (extension.equals("java"))

String comparisons using == compares the objects and not the values.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top