0

我对 WatchService 真的很陌生,我遇到了一个非常有趣的错误。当我在正常模式(运行)下运行我的代码时,它将循环两次 for(Watch event: key1.pollEvents()) 循环并创建两个谷歌日历事件,但如果我使用调试模式单步执行它,它只会添加一个事件。我从网上抓取了几乎所有的代码,试图了解 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) {
          } */
    }

我认为这可能是时间问题,所以我尝试了 sleep try catch,但没有奏效。

4

1 回答 1

0

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

于 2013-07-10T15:30:38.767 回答