FileDocCategorySizeDatePackage
FileObserverTest.javaAPI DocAndroid 1.5 API3439Wed May 06 22:42:02 BST 2009com.android.unit_tests.os

FileObserverTest

public class FileObserverTest extends android.test.AndroidTestCase

Fields Summary
private Observer
mObserver
private File
mTestFile
Constructors Summary
Methods Summary
protected voidsetUp()

        mTestFile = File.createTempFile(".file_observer_test", ".txt"); 
    
protected voidtearDown()

        if (mTestFile != null && mTestFile.exists()) {
            mTestFile.delete();
        }
    
public voidtestRun()

        // make file changes and wait for them
        assertTrue(mTestFile.exists());
        assertNotNull(mTestFile.getParent());
        
        mObserver = new Observer(mTestFile.getParent());
        mObserver.startWatching();

        FileOutputStream out = new FileOutputStream(mTestFile);
        try {
            out.write(0x20);
            waitForEvent(); // open
            waitForEvent(); // modify

            mTestFile.delete();
            waitForEvent(); // delete

            mObserver.stopWatching();
            
            // Ensure that we have seen at least 3 events.
            assertTrue(mObserver.totalEvents > 3);
        } finally {
            out.close();
        }
    
private voidwaitForEvent()

        synchronized (mObserver) {
            boolean done = false;
            while (!done) {
                try {
                    mObserver.wait(2000);
                    done = true;
                } catch (InterruptedException e) {
                }
            }

            Iterator<Map> it = mObserver.events.iterator();

            while (it.hasNext()) {
                Map map = it.next();
                Log.i("FileObserverTest", "event: " + map.get("event").toString() + " path: " + map.get("path"));
            }

            mObserver.events.clear();
        }