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 › try/catch... how it work to check if a file exist
Page Index Toggle Pages: 1
try/catch... how it work to check if a file exist? (Read 2048 times)
try/catch... how it work to check if a file exist?
Nov 25th, 2007, 11:05pm
 
I'm trying to check if a file exist before loading it and I have no idea how to do this. I'm trying with try/cacth. Am I near of the solution? :

for(int i = 0; i < nombreImages; i++) {
   try {
          loadedLines = loadStrings("dataFrame" + i + ".txt");
   }
   catch (Exception e){ // NullPointerException don't work either
          fileExist = false;
          println("exist" + e);
   }
   if (fileExist){
   ...
   }
}
Re: try/catch... how it work to check if a file ex
Reply #1 - Nov 26th, 2007, 9:50am
 
this ought to work (untested) for testing whether a file exists or not:

boolean fileExists(String filename) {

 File file = new File(filename);

 if(!file.exists())
  return false;
   
 return true;
}


This should help:

http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html

Re: try/catch... how it work to check if a file ex
Reply #2 - Nov 26th, 2007, 10:10am
 
dataPath( "filename.ext" );
will give you the path to the sketch's data folder. that is handy in such situations ...

have a look at the openStreamRaw() source. should give you an idea on how to check existance / validity of a file / url.

F
Re: try/catch... how it work to check if a file ex
Reply #3 - Dec 21st, 2008, 7:52pm
 
I ran into the same problem, and fjen's solution worked great.  Here's my code:

Code:


String filename = "foo.txt";

File f = new File(dataPath(filename));

if (f.exists())
{
// do something
}


If you need to look in a specific subdirectory, try:

Code:


String filename = "foo.txt";

File f = new File(dataPath("/subdirectory/" + filename));

if (f.exists())
{
// do something
}
Page Index Toggle Pages: 1