-1

In my javaFx application I am comparing mp4 names with the names of png and if they are the same it will be rendered in an imageView. Problem is the way I did it it also takes the file ending (.mp4 or .png) as name and then says it is different. Is there a way to say the comparison only should be until the last letter before the . ? I tried to use split but it did not really work

this is my current code:

 if (listOfFiles[i].getName().contains(imglistOfFiles[j].getName())) {
                System.out.println("Identische namen" + imglistOfFiles[j].getName());

            } 
kleopatra
  • 51,061
  • 28
  • 99
  • 211
jizang
  • 17
  • 4
  • 2
    See `String` methods: `substring(..)` and `lastIndexOf(..)`. – vsfDawg Sep 15 '20 at 18:54
  • 1
    You basically want to remove the extension from the filename before comparing them, right? Maybe this will help: https://stackoverflow.com/questions/941272/how-do-i-trim-a-file-extension-from-a-string-in-java – Abra Sep 15 '20 at 18:56

1 Answers1

1

You should remove the file extensions part. You can do it with replace() method of String:

if (listOfFiles[i].getName().replaceAll("(\\..+)$","").equals
          (imglistOfFiles[j].getName().replaceAll("(\\..+)$",""))) {
    System.out.println("Identische namen" + imglistOfFiles[j].getName().replaceAll("(\\..+)$",""));

} 

The regex "\\..+$" searches for extensions at the end of the file's name.

Omid.N
  • 824
  • 9
  • 19
  • Hi, I just tried it but it still shows the extension when I for example do this System.out.println(imglistOfFiles[j].getName().replace("\\..+$","")); the if statement still fails. – jizang Sep 15 '20 at 19:23
  • hey thanks, now it works just as I wanted to have it – jizang Sep 15 '20 at 20:07
  • This is a good answer if the file name is like `filename.ext`, but I have seen plenty of files with names like `file.name.ext`. I would use `String::lastIndexOf`. – SedJ601 Sep 15 '20 at 20:43
  • This will also match, eg, `file.mp4` and `file.name.png`, which I don’t think is the intention. You could use something like `replace(“\\.[^\\.]+$”, “”)` – James_D Sep 15 '20 at 21:28