用java1.8在一台虚拟机上建一个java服务,每秒监听/data/1.txt,/var/2.txt,/log/t.txt多个目录下的文件,如果监听到文件有了就把文件复制到/data/file/目录

用java1.8在一台虚拟机上建一个java服务,每秒监听/data/1.txt,/var/2.txt,/log/t.txt多个目录下的文件,如果监听到文件有了就把文件复制到/data/file/目录下然后停止这个目录的文件的监听,继续其他目录文件的监听,通过接口调用开启监听任务把监听的目录和文件名称传递进去返回成功,调用接口返回停止监听具体怎么实现

好的,下面是一个简单的Java服务实现,该服务可以每秒监听多个目录下的文件,如果发现文件变化,就将其复制到指定目录,并停止该目录下文件的监听。

文件监听器实现

import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileWatcherService {

    private final List<WatchService> watchServices = new ArrayList<>();
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public void startWatching(List<String> directories) {
        for (String directory : directories) {
            executorService.execute(() -> {
                try {
                    WatchService watchService = FileSystems.getDefault().newWatchService();
                    Path dir = Paths.get(directory);
                    dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
                    watchServices.add(watchService);
                    WatchKey key;
                    while ((key = watchService.take()) != null) {
                        for (WatchEvent<?> event : key.pollEvents()) {
                            WatchEvent.Kind<?> kind = event.kind();
                            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                                Path filePath = (Path) event.context();
                                Path source = dir.resolve(filePath);
                                Path targetDir = Paths.get("/data/file/");
                                Path target = targetDir.resolve(filePath);
                                Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
                                System.out.println("File copied from " + source + " to " + target);
                                key.cancel();
                            }
                        }
                        key.reset();
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public void stopWatching() {
        for (WatchService watchService : watchServices) {
            try {
                watchService.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        watchServices.clear();
        System.out.println("File watching stopped.");
    }
}

控制器实现

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class FileWatcherController {

    private final FileWatcherService fileWatcherService = new FileWatcherService();

    @PostMapping("/startWatching")
    public String startWatching(List<String> directories) {
        fileWatcherService.startWatching(directories);
        return "File watching started.";
    }

    @PostMapping("/stopWatching")
    public String stopWatching() {
        fileWatcherService.stopWatching();
        return "File watching stopped.";
    }
}

运行服务

你可以将以上代码放在一个Java项目中,并使用Spring Boot来管理依赖项和运行应用程序。确保将监听目录的路径传递给startWatching接口,以开始监听任务。

调用接口

  • 开始监听任务:
bashcurl -X POST -H "Content-Type: application/json" -d '["/data/1.txt", "/var/2.txt", "/log/t.txt"]' http://localhost:8080/startWatching 
  • 停止监听任务:
bashcurl -X POST http://localhost:8080/stopWatching 

这样,你就可以通过接口调用开始和停止监听任务了。

上面的功能作为单独的一个服务启动有端口

好的,如果需要将上面的功能作为一个独立的服务启动,并且希望该服务监听特定的端口,可以使用Spring Boot来实现。

文件监听器服务

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.*;

@Service
public class FileWatcherService {

    @Value("${watcher.directories}")
    private String[] directories;

    private final WatchService watchService = FileSystems.getDefault().newWatchService();

    @PostConstruct
    public void startWatching() {
        try {
            for (String directory : directories) {
                Path dir = Paths.get(directory);
                dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            try {
                while (true) {
                    WatchKey key = watchService.take();
                    for (WatchEvent<?> event : key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();
                        if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            Path filePath = (Path) event.context();
                            Path source = (Path) key.watchable();
                            Path targetDir = Paths.get("/data/file/");
                            Path target = targetDir.resolve(filePath);
                            Files.copy(source.resolve(filePath), target, StandardCopyOption.REPLACE_EXISTING);
                            System.out.println("File copied from " + source.resolve(filePath) + " to " + target);
                            key.cancel();
                        }
                    }
                    key.reset();
                }
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

控制

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class FileWatcherController {

    @Autowired
    private FileWatcherService fileWatcherService;

    @PostMapping("/startWatching")
    public String startWatching(List<String> directories) {
        fileWatcherService.startWatching(directories);
        return "File watching started.";
    }
}

应用配置

application.properties 中添加以下配置:

watcher.directories=/data, /var, /log
server.port=8081

主应用程序

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

运行服务

以上代码是一个完整的Spring Boot应用程序。可以使用mvn spring-boot:run命令来运行应用程序,它将在端口8081上启动文件监听器服务。

调用接口

  • 开始监听任务:
bashcurl -X POST -H "Content-Type: application/json" -d '["/data", "/var", "/log"]' http://localhost:8081/startWatching 

这样,你就可以作为一个单独的服务启动,并监听指定的端口。

用java1.8在虚拟机上建一个应用,每秒监听/data/1.txt,/var/2.txt,/log/t.txt多个目录下的文件,如果监听到文件有了就把文件复制到/data/file/目录下然后停止这个目录的文件的监听,继续其他目录文件的监听,通过接口调用开启监听任务把监听的目录和文件名称传递进去返回成功,调用接口返回停止监听,目录结构也显示出来,路径通过接口参数传递不要用配置文件

好的,你希望实现一个监听多个目录下文件的Java应用,并提供接口来开始和停止监听任务,并且这些目录和文件名称作为接口参数传递。以下是一个实现的示例。

文件监听服务

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class FileWatcherService {

    private final ExecutorService executorService = Executors.newFixedThreadPool(5);
    private final Map<WatchKey, Path> watchKeyPathMap = new HashMap<>();

    public void startWatching(List<String> directories) {
        for (String directory : directories) {
            executorService.execute(() -> {
                try {
                    Path dir = Paths.get(directory);
                    WatchService watchService = FileSystems.getDefault().newWatchService();
                    WatchKey watchKey = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
                    watchKeyPathMap.put(watchKey, dir);

                    WatchKey key;
                    while ((key = watchService.take()) != null) {
                        Path parentDirectory = watchKeyPathMap.get(key);
                        for (WatchEvent<?> event : key.pollEvents()) {
                            WatchEvent.Kind<?> kind = event.kind();
                            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                                Path filePath = (Path) event.context();
                                Path source = parentDirectory.resolve(filePath);
                                Path targetDir = Paths.get("/data/file/");
                                Path target = targetDir.resolve(filePath);
                                Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
                                System.out.println("File copied from " + source + " to " + target);
                                key.cancel();
                            }
                        }
                        key.reset();
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public void stopWatching() {
        executorService.shutdown();
        watchKeyPathMap.clear();
        System.out.println("File watching stopped.");
    }
}

控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/file-watcher")
public class FileWatcherController {

    @Autowired
    private FileWatcherService fileWatcherService;

    @PostMapping("/start")
    public String startWatching(@RequestBody List<String> directories) {
        fileWatcherService.startWatching(directories);
        return "File watching started for directories: " + directories;
    }

    @PostMapping("/stop")
    public String stopWatching() {
        fileWatcherService.stopWatching();
        return "File watching stopped.";
    }
}

主应用程序

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

运行服务

你可以将以上代码放在一个Spring Boot项目中,并运行该应用程序。它将在默认的端口上启动(通常是8080)。

调用接口

  • 开始监听任务:
bashcurl -X POST -H "Content-Type: application/json" -d '["/data/1.txt", "/var/2.txt", "/log/t.txt"]' http://localhost:8080/file-watcher/start 
  • 停止监听任务:
bashcurl -X POST http://localhost:8080/file-watcher/stop 

这样,你就可以通过接口调用开始和停止监听任务了,同时监听多个目录下的文件。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值