We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › using substring to check file types
Page Index Toggle Pages: 1
using substring to check file types (Read 400 times)
using substring to check file types
May 19th, 2009, 12:58pm
 
Hey Everyone, was hoping that maybe someone out there would know what I am doing wrong.
  I am in a sketch that allows the user to selectInput(). I then want to find the file type (by finding the last three letters of the filename/path). That is all working fine, since I am printing as I go I know it is getting the correct substring. However, when I run the code below, every time, even if the extension is a .jpg or other acceptable format, there is a problem within my conditionals because I always get my _FileError2.
  The code below is a method where userfile is a global variable. The way I have it set up always works except when I threw in the substring check. Ideally I only want it to return true if the user chose a proper file type.
  Any help would be greatly appreciated.



boolean ChooseFile()
{
String _FileError2 = "The only acceptable file types are: .gif, .jpg, .tga, and .png.";
String userfile = selectInput();
int UserFileNameStringLength = userfile.length();
String extension = userfile.substring(UserFileNameStringLength-3);
print(extension);

if(extension != "jpg") //&& extension != "gif" && extension != "tga" && extension != "png")
 {
 println(_FileError2);
 exit();
 return false;
 }

 
 
if(userfile==null)
 {
 println(_FileError1);
 exit();
   return false;
 }
 
else
 {return true;}
 
}
Re: using substring to check file types
Reply #1 - May 19th, 2009, 1:09pm
 
Ah, selectInput() doesn't take a file filter Of course, it might be too advanced...
It is better to show only the accepted files, like we do with JFileChooser, but well, let's go the simpler way.

The error is obvious for anybody with a little Java experience, and confusing for the beginners (we all have been one day!).
You cannot use (in general) == nor != with strings in Java/Processing (see remarks at String).
You have to write: extension.equals("jpg"), for example.
But since you are there, you can make it even simpler, using endsWith():
Code:
String userfile = selectInput();
userfile = userfile.toLowerCase();
if (!userfile.endsWith("jpg") && !userfile.endsWith("gif") && !userfile.endsWith("tga") && !userfile.endsWith("png")) {
Complain();

etc.
Page Index Toggle Pages: 1