WatchService循环运行两次,除非在调试模式下执行



我真的是WatchService的新手,我遇到了一个非常有趣的bug。当我在正常模式(run)下运行代码时,它将循环通过for(Watch event:key1.pollEvents())循环两次,并创建两个google calander事件,但如果我使用调试模式逐步通过它,它只添加一个事件。我从网上获取了几乎所有的代码,试图了解WatchService是如何工作的。我真的不知道我在这里做什么,所以任何帮助都会很棒。这是我的代码

/*
 * Copyright (c) 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.api.services.samples.calendar.cmdline;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.Lists;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Event.Reminders;
import com.google.api.services.calendar.model.EventDateTime;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TimeZone;
/**
 * @author Yaniv Inbar
 */
public class myCalendar {
  /**
   * Be sure to specify the name of your application. If the application name is {@code null} or
   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
   */
  private static final String APPLICATION_NAME = "";
  /** Global instance of the HTTP transport. */
  private static HttpTransport HTTP_TRANSPORT;
  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static com.google.api.services.calendar.Calendar client;
  static final java.util.List<Calendar> addedCalendarsUsingBatch = Lists.newArrayList();
  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(myCalendar.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
          + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up file credential store
    FileCredentialStore credentialStore = new FileCredentialStore(
        new File(System.getProperty("user.home"), ".credentials/calendar.json"), JSON_FACTORY);
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets,
        Collections.singleton(CalendarScopes.CALENDAR)).setCredentialStore(credentialStore).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }
  public static void main(String[] args) throws IOException {
    Path dir = Paths.get("C:\Users\kdevocht\Dropbox\Apps\Attachments\kjdevocht@gmail.com\");
    WatchService service = FileSystems.getDefault().newWatchService();
    WatchKey key = dir.register(service, ENTRY_MODIFY);
    System.out.println("Watching directory: "+dir.toString());
    for(;;){
        WatchKey key1;
        try {
            key1 = service.take();
        } catch (InterruptedException x) {
            break;
        }
        for (WatchEvent<?> event: key1.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }
            WatchEvent<Path> ev = (WatchEvent<Path>)event;
            Path filename = ev.context();
            Path child = dir.resolve(filename);
            System.out.println("File: "+child.toString()+" modified.");
            try{
              try {
                try {
                  // initialize the transport
                  HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
                  // authorization
                  Credential credential = authorize();
                  // set up global Calendar instance
                  client = new com.google.api.services.calendar.Calendar.Builder(
                      HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
                      APPLICATION_NAME).build();
                  // run commands
                  Calendar calendar = client.calendars().get("kjdevocht@gmail.com").execute();
                  addEvent(calendar, child.toString());
                } catch (IOException e) {
                  System.err.println(e.getMessage());
                }
              } catch (Throwable t) {
                t.printStackTrace();
              }
              //System.exit(1);;
            }catch(Exception x){
                x.printStackTrace();
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
/*        try {
          Thread.sleep(5000);
          } catch(InterruptedException e) {
          } */
    }

我想这可能是时间问题,所以我尝试了一个睡眠尝试接球,但没有成功。

所以看起来一切都很好。我用记事本++在我正在观看的目录中编辑一个文件。经过一些研究,似乎进行了两次修改,因此记录了两个事件。有些人建议存储文件的时间戳,只在文件更改时做出反应,这似乎可以过滤掉多个事件。对我和我正在做的事情来说,我只是改为观看一场创造活动。这现在工作得很好,没有任何问题

相关内容

  • 没有找到相关文章

最新更新