Check for an existing file using a loop

I want to check for an existing file using a while loop. Now the problem is if you use something like this:

while (file.exists()) {
        text.setText("Some text appears");
        text.setTextColor(Color.RED);
}

      

my program always seems to be unresponsive at all. Is it because my loop is somehow an infinite loop? Or why it doesn't work correctly.

I am currently using a simple one if statement

, but I don't like it because it doesn't update immediately when the file exists.

EDIT: I want: I suggest a file to download. My app has text that says "Not Available". I want to change the text right after the file exists, for example "File available".

+3


source to share


4 answers


If you want to periodically check if a file exists, you must do so using an asynchronous task or timer.

    TTimerTask task = new TimerTask() {

        @Override
        public void run() {
            // Here you do whatever you want
        }
    };

    Timer timer = new Timer();
    timer.schedule(task, 0,30000);

      



This will check the file every thirty seconds.

You can find more information at http://www.mkyong.com/java/jdk-timer-scheduler-example/

+3


source


Your program goes into an infinite loop, since the condition inside the loop while

will always be there true

if the file is present.

You need to check the following:

File file = new File(subDir.getPath() + "somefile.txt");  
boolean exists = file.exists();  

if (!exists) {  
// It returns false if File or directory does not exist 
}
else
{
  //Update here
}

      



And if you want to test it inside a loop, try like this:

while (true)
{
  File file = new File(subDir.getPath() + "somefile.txt");  
  boolean exists = file.exists();  

  if (!exists) {  
    // It returns false if File or directory does not exist 
    return;
  }
  else
  {
    //Update here
  }
}

      

+2


source


If the file exists, it will appear in the while loop and continue the loop, because the file exists, you will have to make the file not exist in the while loop ...

The best thing you need to do is get your program to run without the while loop ... as you mentioned with the IF function, and then slowly over time implement (Test) the new function (while loop) into the equation.

What to fix in the while loop ... What happens to the file when it enters the loop and how it exits the loop. The current position is not how the file still exists.

+1


source


Ok, so when another person checks the file, does the program exit if the file doesn't exist? I mean you can't just check the file forever. I suppose you could put it on a thread and run it with a little waiting inside a while loop, but the overhead is ... sheesh!

Is this a specific screen inside your program? Is it possible for a person to be able to exit this "found / not found" page? Perhaps I could write a snippet, but I need more information. :)

0


source







All Articles