Check if file exists or not

As the title says, I want to check whether a file exists. I am not trying to look at the data folder because I think you just have to use dataFile().
At the moment I just have to see if a specific file is in the sketch folder.
I have written the following code.

String[] lines1 = loadStrings("positions1.txt"); // file exists or not but you get a 
  if (lines1==null){
    println("nothing is here");
  }

However this returns some sort of error message about the file might not exist (obviously) and if I have to look at over a hundred files it can become quite a lot of error messages.
Is there any simple way to check whether a file exists without getting this kind of error message?

2 Likes

Hi

I haven’t checked if this applies in this case, but you may use a try/catch block to discard any thrown exceptions.

Check if (!dataFile(name).isFile()) table = createAndSaveTableFile(name);
at file “Card_Functions.pde” within function loadCards():

2 Likes

Sorry but this didn’t help because when I write the following:

BufferedReader reader;
String line;
boolean stopReading=false;
 
void setup() {
  // Open the file from the createWriter() example
  reader = createReader("positions1.txt");
  while(!stopReading){
    try {
      line = reader.readLine();
    } catch (IOException e) {
      e.printStackTrace();
      line = null;
    }
    if (line == null) {
    // Stop reading because of an error or file is empty
      println("there is no more text");
      stopReading=true;
      noLoop();  
    } else {
      println(line);
    }
  }
}
 
void draw() {
  
}

it gives an nullpointerexception. It does this because I have changed the filename. It would be great if I can just change the filename and either it says there is no text if the file doesn’t exists and print the lines if the file exists

Add if (!dataFile("positions1.txt").isFile()) exit();
before reader = createReader("positions1.txt");

This just gives me a NullPointerException sadly.

BufferedReader reader;
String line;
boolean stopReading=false;
 
void setup() {
  // Open the file from the createWriter() example
  if (!dataFile("positions1.txt").isFile()) exit();
  reader = createReader("positions1.txt");
  while(!stopReading){
    try {
      line = reader.readLine();
    } catch (IOException e) {
      e.printStackTrace();
      line = null;
    }
    if (line == null) {
    // Stop reading because of an error or file is empty
      println("there is no more text");
      stopReading=true;
      noLoop();  
    } else {
      println(line);
    }
  }
}
 
void draw() {
  
}

The problem seems to be in the catch()-part of the code. I have looked around but I can’t find anything about catching a NullPointerException.