当前位置: 首页>>代码示例>>Java>>正文


Java WatchService类代码示例

本文整理汇总了Java中name.pachler.nio.file.WatchService的典型用法代码示例。如果您正苦于以下问题:Java WatchService类的具体用法?Java WatchService怎么用?Java WatchService使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


WatchService类属于name.pachler.nio.file包,在下文中一共展示了WatchService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testNewSingleThreadExecutor

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
/**
 * Tests {@link FileSystemFactory#newWatchService()}.
 *
 * @throws ClosedWatchServiceException if the newly-created service is closed
 * @throws IOException if the test fails
 * @throws InterruptedException hopefully never
 */
@Test
public void testNewSingleThreadExecutor() throws ClosedWatchServiceException, IOException, InterruptedException {
    WatchService service = new FileSystemFactory().newWatchService();
    try {
        assertNotNull(service);
        assertNull(service.poll()); // verifies the service is not closed
    } finally {
        if (service != null) {
            try {
                service.close();
            }catch(IOException ex) {
                //trap
            }
        }
    }
}
 
开发者ID:sworisbreathing,项目名称:sfmf4j,代码行数:24,代码来源:FileSystemFactoryTest.java

示例2: testOneTakerClosing

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testOneTakerClosing() throws IOException, InterruptedException{
	// test that closing a WatchService makes it raise a
	// ClosedWatchServiceException from a take() call
	WatchService watcher = Bootstrapper.newWatchService();
	SingleWatchKeyTaker swkt = new SingleWatchKeyTaker(watcher);

	swkt.start();

	// this should make sure that swkt is actually running and waiting in WatchService.take().
	wait(200);

	watcher.close();

	swkt.join(1000);
	Assert.assertFalse(swkt.isAlive());
	Assert.assertTrue(swkt.closedException);
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:19,代码来源:JDK7Test.java

示例3: newWatchService

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
/**
* Creates a new WatchService. This is a shortcut for calling
* <code>FileSystems.getDefault().newWatchService()</code> and
* is not source-compatible to JDK7
* @return	a new WatchService implementation instance.
* @see name.pachler.nio.file.FileSystem#newWatchService()
* @see name.pachler.nio.file.FileSystems#getDefault()
*/
  public static WatchService newWatchService(){
WatchService ws = null;
try {
	if(!forcePolling){
		switch(ostype){
			case OSTYPE_LINUX:
				ws = new LinuxPathWatchService();
				break;
			case OSTYPE_WINDOWS:
				ws = new WindowsPathWatchService();
				break;
			case OSTYPE_BSD:
				ws = new BSDPathWatchService();
				break;
		}
	}
} catch(Throwable t){
	Logger.getLogger(Bootstrapper.class.getName()).log(Level.WARNING, null, t);
} finally {
	// if for whatever reason we don't have a
	// WatchService, we'll create a polling one as fallback.
	if(ws == null)
		ws = new PollingPathWatchService();
	return ws;
}
  }
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:35,代码来源:Bootstrapper.java

示例4: testPollTimeout

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public void testPollTimeout() throws IOException, ClosedWatchServiceException, InterruptedException{

	// test to check if the polling timeout works properly.
	// The timeouts don't need to be exact (they can't be), but
	// they should at least be reasonably close (we assume 10% delta here)
	// to the specified timeout value.
	WatchService watcher = null;
	try {
		watcher = Bootstrapper.newWatchService();

		File dir = createTempDir("testPollTimeout");

		Path path = Paths.get(dir.getPath());
		WatchKey key = path.register(watcher, ENTRY_CREATE);

		long timeout = 2500;

		long startTime = System.currentTimeMillis();

		watcher.poll(timeout, TimeUnit.MILLISECONDS);

		long endTime = System.currentTimeMillis();

		long elapsed = endTime - startTime;
		assertEquals(timeout, elapsed, timeout*.1);

		timeout = 2000;
		startTime = System.currentTimeMillis();
		watcher.poll(timeout/1000, TimeUnit.SECONDS);

		endTime = System.currentTimeMillis();

		elapsed = endTime - startTime;
		assertEquals(timeout, elapsed, timeout*.1);
	} finally {
		if(watcher != null)
			watcher.close();
	}
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:41,代码来源:JDK7Test.java

示例5: testTakeFirstThenRegister

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testTakeFirstThenRegister() throws IOException, InterruptedException{
	// Tests the following case:
	// * A thread calls take on a WatchService that has no paths registered
	//	yet. take() will block.
	// * Another thread registers a path afterwards, and then creates
	//	a file in the watched path.
	// * The first thread should return a watch key now
	WatchService watcher = Bootstrapper.newWatchService();
	SingleWatchKeyTaker swkt = new SingleWatchKeyTaker(watcher);

	swkt.start();

	wait(200);	// give the swkt thread time to call take()...

	File dir = createTempDir("testTakeFirstThenRegister");
	Path path = Bootstrapper.newPath(dir);
	WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
	File file = new File(dir, "test");
	file.createNewFile();
	file.deleteOnExit();

	// the take() call in the swkt thread should have returned by now
	// and returned the key
	long joinTimeout = 1000;

	if(watcher instanceof PollingPathWatchService)
		joinTimeout = (long)(1.5f * ((PollingPathWatchService)watcher).getPollInterval());	// longer timeout if we have a polling service

	swkt.join(joinTimeout);

	Assert.assertFalse(swkt.isAlive());
	Assert.assertTrue(swkt.watchKey == key);

	watcher.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:37,代码来源:JDK7Test.java

示例6: testRegister

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testRegister() throws InterruptedException, IOException{
	WatchService service = Bootstrapper.newWatchService();

	File dir = createTempDir("watched-dir");
	Path path = Bootstrapper.newPath(dir);

	WatchKey key1 = path.register(service, StandardWatchEventKind.ENTRY_CREATE);

	File file = new File(dir, "file");
	file.createNewFile();

	wait(200);

	WatchKey resultKey1 = service.poll(200, TimeUnit.MILLISECONDS);
	assertTrue(resultKey1 == key1);
	List<WatchEvent<?>> list1 = resultKey1.pollEvents();
	assertTrue(listContainsEvent(list1, ENTRY_CREATE, "file"));
	assertTrue(resultKey1.reset());

	WatchKey key2 = path.register(service, ENTRY_CREATE, ENTRY_DELETE);

	assertTrue(key1 == key2);

	file.delete();

	WatchKey resultKey2 = service.poll(200, TimeUnit.MILLISECONDS);
	assertTrue(resultKey2 == key2);
	List<WatchEvent<?>> list2 = resultKey2.pollEvents();
	assertTrue(listContainsEvent(list2, ENTRY_DELETE, "file"));
	assertTrue(resultKey2.reset());

	service.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:35,代码来源:JDK7Test.java

示例7: testACCURATE

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testACCURATE() throws InterruptedException, IOException{
	WatchService service = Bootstrapper.newWatchService();

	File dir = createTempDir("watched-dir");
	Path path = Bootstrapper.newPath(dir);

	// ensure that selected platforms support ACCURATE
	boolean platformSupportsACCURATE =
		System.getProperty("os.name").contains("Windows")
	||	System.getProperty("os.name").contains("Linux");
	WatchKey key1;
	try {
		key1 = path.register(service, new WatchEvent.Kind[]{StandardWatchEventKind.ENTRY_CREATE}, ExtendedWatchEventModifier.ACCURATE);
	}catch(UnsupportedOperationException uox){
		// implementation reports that ACCURATE is not supported,
		// so ensure that that's true:
		assertFalse(platformSupportsACCURATE);
		return;
	}

	File file = new File(dir, "file");
	file.createNewFile();
	file.delete();

	wait(200);

	WatchKey resultKey1 = service.poll(200, TimeUnit.MILLISECONDS);
	List<WatchEvent<?>> list1 = resultKey1.pollEvents();
	assertTrue(resultKey1 == key1);
	assertTrue(listContainsEvent(list1, ENTRY_CREATE, "file"));
	assertFalse(listContainsEvent(list1, ENTRY_DELETE, "file"));
	assertTrue(resultKey1.reset());

	service.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:37,代码来源:JDK7Test.java

示例8: testInvalidationByCancel

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testInvalidationByCancel() throws IOException, InterruptedException{
	// test for KEY_INVALID events in case the user manually cancels
	// the watch key by calling WatchKey.cancel().
	WatchService service = FileSystems.getDefault().newWatchService();

	File dir = createTempDir("testInvalidationByCancel");
	Path path = Paths.get(dir.toString());

	WatchKey key = path.register(service, ENTRY_CREATE, KEY_INVALID);

	// invalidation by user
	key.cancel();

	assertFalse(key.isValid());

	// Because we're listening for KEY_INVALID events, the key still
	// needs to be queued
	WatchKey k = service.poll();
	assertSame(key, k);

	List<WatchEvent<?>> events = k.pollEvents();
	assertTrue(events.size()==1);
	assertTrue(listContainsEvent(events, KEY_INVALID, null));

	service.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:28,代码来源:JDK7Test.java

示例9: testInvalidationByDelete

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testInvalidationByDelete() throws IOException, InterruptedException{
	// test for KEY_INVALID events in case the Path for which they
	// key was registered is removed
	WatchService service = FileSystems.getDefault().newWatchService();

	File dir = createTempDir("testInvalidationByDelete");
	Path path = Paths.get(dir.toString());

	WatchKey key = path.register(service, ENTRY_CREATE, KEY_INVALID);

	// invalidation by deleting the watched path
	boolean deleted = dir.delete();
	assertTrue(deleted);	// if delete fails, we can't test

	wait(500);	// wait a bit so that the deletion can propagate
	// (Windows appears to be specifically slow here...)

	// Because we're listening for KEY_INVALID events, the key still
	// should still be queued
	WatchKey k = service.poll();
	assertSame(key, k);

	// key should now be invalid
	assertFalse(key.isValid());

	List<WatchEvent<?>> events = k.pollEvents();
	assertTrue(events.size()==1);
	assertTrue(listContainsEvent(events, KEY_INVALID, null));

	service.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:33,代码来源:JDK7Test.java

示例10: register

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Override
  public WatchKey register(WatchService watcher, Kind<?>... events) throws IOException {
return register(watcher, events, new WatchEvent.Modifier[0]);
  }
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:5,代码来源:PathImpl.java

示例11: SingleWatchKeyTaker

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
public SingleWatchKeyTaker(WatchService watcher) {
	this.watcher = watcher;
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:4,代码来源:JDK7Test.java

示例12: testTwoTakerThreads

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public void testTwoTakerThreads() throws IOException, InterruptedException{
	// WatchKeys for two distinct directories are created. Two threads
	// are created, each calling take() once. In each observed directory,
	// a single file is created.
	// The expected result is that each thread receives one of the WatchKeys
	// as a return value from take().

	WatchService w = Bootstrapper.newWatchService();

	SingleWatchKeyTaker swkt1 = new SingleWatchKeyTaker(w, "swkt1");
	SingleWatchKeyTaker swkt2 = new SingleWatchKeyTaker(w, "swkt2");

	File dir1 = createTempDir("dir1");
	Path path1 = Bootstrapper.newPath(dir1);
	WatchKey wk1 = path1.register(w, StandardWatchEventKind.ENTRY_CREATE);

	File dir2 = createTempDir("dir2");
	Path path2 = Bootstrapper.newPath(dir2);
	WatchKey wk2 = path2.register(w, StandardWatchEventKind.ENTRY_CREATE);

	swkt1.start();
	swkt2.start();

	File file1 = new File(dir1, "file1");
	file1.createNewFile();
	file1.deleteOnExit();
	File file2 = new File(dir2, "file2");
	file2.createNewFile();
	file2.deleteOnExit();

	synchronized(this){
		wait(1000);	// wait a second to give threads time to process events
	}

	// because threads each take a single watch key and terminate straight
	// after, they should all be dead by now
	Assert.assertFalse(swkt1.isAlive());
	Assert.assertFalse(swkt2.isAlive());

	// put all received watch keys into a set
	Set<WatchKey> paths = new HashSet<WatchKey>();
	paths.add(swkt1.watchKey);
	paths.add(swkt2.watchKey);

	// check that the watch keys the threads received are distinct, and
	// that they were the keys that we used
	Assert.assertTrue(swkt1.watchKey != swkt2.watchKey);
	Assert.assertTrue(paths.contains(wk1));
	Assert.assertTrue(paths.contains(wk2));

	w.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:54,代码来源:JDK7Test.java

示例13: testOneTaker

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testOneTaker() throws IOException, InterruptedException{
	WatchService watcher = Bootstrapper.newWatchService();

	File dir = createTempDir("dir1");
	Path path = Bootstrapper.newPath(dir);
	WatchKey wk = path.register(watcher, StandardWatchEventKind.ENTRY_CREATE);

	// wait for 200ms - should return no key
	WatchKey key = watcher.poll(200, TimeUnit.MILLISECONDS);
	assertNull(key);

	File file1 = new File(dir, "file1");
	file1.createNewFile();

	wait(200);

	key = watcher.take();
	assertNotNull(key);
	List<WatchEvent<?>> eventList = key.pollEvents();
	assertTrue(eventList.size() == 1);
	WatchEvent event = eventList.get(0);
	assertEquals(event.context(), Bootstrapper.newPath(new File("file1")));
	assertEquals(event.kind(), ENTRY_CREATE);

	key.reset();

	File file2 = new File(dir, "file2");
	file2.createNewFile();

	wait(200);

	key = watcher.take();
	assertNotNull(key);
	eventList = key.pollEvents();
	assertTrue(eventList.size() == 1);
	event = eventList.get(0);
	assertEquals(event.context(), Bootstrapper.newPath(new File("file2")));
	assertEquals(event.kind(), ENTRY_CREATE);

	key.reset();

	// test file with single-character file name
	File file3 = new File(dir, "3");
	file3.createNewFile();

	wait(200);

	key = watcher.take();
	assertNotNull(key);
	eventList = key.pollEvents();
	assertTrue(eventList.size() == 1);
	event = eventList.get(0);
	assertEquals(event.context(), Bootstrapper.newPath(new File("3")));
	assertEquals(event.kind(), ENTRY_CREATE);

	watcher.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:59,代码来源:JDK7Test.java

示例14: testOneTakerThreaded

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public synchronized void testOneTakerThreaded() throws IOException, InterruptedException{
	// WatchKeys for two distinct directories are created. Two threads
	// are created, each calling take() once. In each observed directory,
	// a single file is created.
	// The expected result is that each thread receives one of the WatchKeys
	// as a return value from take().

	WatchService watcher = Bootstrapper.newWatchService();

	SingleWatchKeyTaker swkt = new SingleWatchKeyTaker(watcher);

	File dir = createTempDir("dir1");
	Path path = Bootstrapper.newPath(dir);
	WatchKey wk = path.register(watcher, StandardWatchEventKind.ENTRY_CREATE);

	File file = new File(dir, "file1");
	file.createNewFile();
	file.deleteOnExit();

	WatchKey key = watcher.take();
	assertTrue(key != null);
	boolean resetSuccessful = key.reset();
	assertTrue(resetSuccessful);

	swkt.start();

	File file2 = new File(dir, "file2");
	file2.createNewFile();
	file2.deleteOnExit();

	wait(200);	// wait a second to give threads time to process events

	// because threads each take a single watch key and terminate straight
	// after, they should all be dead by now
	Assert.assertFalse(swkt.isAlive());

	// check that the watch keys the threads received are distinct, and
	// that they were the keys that we used
	Assert.assertTrue(swkt.watchKey == wk);

	watcher.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:44,代码来源:JDK7Test.java

示例15: testRecursiveWatch

import name.pachler.nio.file.WatchService; //导入依赖的package包/类
@Test
public void testRecursiveWatch() throws IOException, InterruptedException{
	WatchService service = Bootstrapper.newWatchService();

	// test non-recursive watch first: make sure that changes
	// to files in a child directory are ignored

	File dir = createTempDir("watched-dir");
	Path path = Bootstrapper.newPath(dir);
	File subdir = new File(dir, "subdir");
	subdir.mkdir();

	WatchKey key1 = path.register(service, StandardWatchEventKind.ENTRY_CREATE);

	File file1 = new File(subdir, "file1");
	file1.deleteOnExit();
	file1.createNewFile();

	// the file that has just been created must be ignored.
	WatchKey result1 = service.poll(200, TimeUnit.MILLISECONDS);
	assertNull(result1);

	WatchKey key2;
	try {
		WatchEvent.Kind[] eventKinds = { StandardWatchEventKind.ENTRY_CREATE };
		key2 = path.register(service, eventKinds, ExtendedWatchEventModifier.FILE_TREE);
	} catch (UnsupportedOperationException uox){
		// on platforms other than Windows, we expect an illegal argument
		// exception, because only Windows currently implements the
		// FILE_TREE modifier.
		if(!System.getProperty("os.name").contains("Windows") || Bootstrapper.isForcePollingEnabled())
			return;
		throw uox;
	}

	File file2 = new File(subdir, "file2");
	file2.deleteOnExit();
	file2.createNewFile();

	WatchKey result2 = service.poll(200, TimeUnit.MILLISECONDS);
	assertTrue(result2 == key2);

	service.close();
}
 
开发者ID:sworisbreathing,项目名称:jpathwatch,代码行数:45,代码来源:JDK7Test.java


注:本文中的name.pachler.nio.file.WatchService类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。