最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用SpringBoot讀取Windows共享文件的代碼示例

 更新時間:2024年11月04日 10:44:00   作者:Jerryean99  
在現(xiàn)代企業(yè)環(huán)境中,文件共享是一個常見的需求,Windows共享文件夾(SMB/CIFS協(xié)議)因其易用性和廣泛的兼容性,成為了許多企業(yè)的首選,在Java應用中,尤其是使用Spring Boot框架時,如何讀取Windows共享文件是一個值得探討的話題,本文介紹了使用SpringBoot讀取Windows共享文件

一、背景

在現(xiàn)代企業(yè)環(huán)境中,文件共享是一個常見的需求。Windows共享文件夾(SMB/CIFS協(xié)議)因其易用性和廣泛的兼容性,成為了許多企業(yè)的首選。在Java應用中,尤其是使用Spring Boot框架時,如何讀取Windows共享文件是一個值得探討的話題。本文將介紹如何在Spring Boot應用中實現(xiàn)這一功能。

二、需求概述

項目需要對接各種的設備儀器,有很多的類型,例如串口傳輸、讀取數(shù)據(jù)庫、TCP/IP等等方式,這些解決辦法是非常多的,但是有幾臺機器是做完實驗就會在本地生成文件,一開始我們的想法也比較多,比如業(yè)務人員每天進行導入操作,后續(xù)考慮到盡量減小業(yè)務人員的操作,想到一個簡單的方式就是定時讀取每個機器電腦上的共享文件,根據(jù)它的修改時間讀取所需的數(shù)據(jù)文件。

三、準備工作:windows共享文件夾配置

在windows系統(tǒng)中已經(jīng)創(chuàng)建并共享了一個文件夾,記錄下共享文件夾的網(wǎng)絡路徑,例如:\\服務器名\共享文件夾名。

確保你的Spring Boot應用所在的系統(tǒng)有權訪問該共享文件夾。

配置的流程可以在網(wǎng)上檢索一下,網(wǎng)上的示例也特別特別多,說明一下:可以單獨建立一個共享的用戶
例如用戶名:share 密碼 123456

四、代碼示例

4.1 定時讀取共享文件任務Task

@Component
@Slf4j
public class ReadShareFilesTask {

    @Resource
    InspectEquipmentInfoService inspectEquipmentInfoService;

    /**
     * 現(xiàn)在暫定每天執(zhí)行
     */
    @Scheduled(cron = "0 0 12 * * ?")
    public void executeReadShareFiles() {
        LocalDateTime dateTime = LocalDateTime.now().minusDays(1);
        List<InspectEquipmentInfo> equipmentInfos = inspectEquipmentInfoService.lambdaQuery().eq(InspectEquipmentInfo::getEquipmentType, EquipmentTypeEnum.FILE_SHARING.getCode()).list();
        equipmentInfos.forEach(equipmentInfo -> {
            try {
                log.info("開始讀取設備:{}, 設備名稱:{}, 設備ip:{}", equipmentInfo.getEquipmentCode(), equipmentInfo.getEquipmentName(), equipmentInfo.getEquipmentAddr());
                FileReadStrategy fileReadStrategy = ClassExecuteServiceFactory.getFileReadStrategy(equipmentInfo.getEquipmentCode());
                ValidationUtils.checkNotNull(fileReadStrategy, "策略未找到");
                fileReadStrategy.listFile(equipmentInfo.getEquipmentAddr(),dateTime);
            } catch (Exception e) {
                log.error("讀取設備:{}, 設備名稱:{}, 設備ip:{} 失敗", equipmentInfo.getEquipmentCode(), equipmentInfo.getEquipmentName(), equipmentInfo.getEquipmentAddr(), e);
            }
        });
    }
}

4.2 工廠類

@Component
public class ClassExecuteServiceFactory implements ApplicationContextAware {

    private final static Map<String, FileReadStrategy> CLASS_CODE_ABSTRACT_CLASS_HANDLE_MAP = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, FileReadStrategy> types = applicationContext.getBeansOfType(FileReadStrategy.class);
        types.values().forEach(e -> CLASS_CODE_ABSTRACT_CLASS_HANDLE_MAP.putIfAbsent(e.getCode(), e));
    }

    public static FileReadStrategy getFileReadStrategy(String code) {
        return CLASS_CODE_ABSTRACT_CLASS_HANDLE_MAP.get(code);
    }
}

4.3 文件讀取接口策略

public interface FileReadStrategy {

    String getCode();

    void listFile(String ip, LocalDateTime dateTime);

    void handleFileRead(InputStream inputStream, InspectEquipmentInfo info);
}

4.4 策略實現(xiàn)類

@Component
@Slf4j
public class SpectrometerFileReadStrategy implements FileReadStrategy {

    @Resource
    private InspectEquipmentInfoService equipmentInfoService;

    @Resource
    private InspectEquipmentRecordService recordService;

    @Resource
    private ReceiveEquipmentApi receiveEquipmentApi;

    @Override
    public String getCode() {
        return ShareFilesAddressEnum.CODE.getCode();
    }

    @Override
    public void listFile(String ip, LocalDateTime dateTime) {
        InspectEquipmentInfo equipmentInfo = equipmentInfoService.lambdaQuery().eq(InspectEquipmentInfo::getEquipmentAddr, ip).one();
        if (ObjectUtil.isEmpty(equipmentInfo)) {
            log.error("該設備未配置到設備表當中,設備地址 {}", ip);
            return;
        }
        SmbFileReader.listSmbFile(equipmentInfo, dateTime);
    }

    @Override
    public void handleFileRead(InputStream inputStream, InspectEquipmentInfo info) {
        try {
            if (inputStream == null) {
                log.error("無法找到ICP光譜儀CSV文件");
                return;
            }
            //根據(jù)文件流解析數(shù)據(jù)
      }

4.5 讀取共享文件流通用類

@Slf4j
public class SmbFileReader {

    public static void listSmbFile(InspectEquipmentInfo info, LocalDateTime dateTime) {
        String path = info.getPath();
        String ip = info.getEquipmentAddr();
        String user = info.getUser();
        String pass = info.getPass();
        String suffix = info.getSuffix();
        String code = info.getEquipmentCode();
        SMBClient client = new SMBClient();
        try (Connection connection = client.connect(ip)) {
            AuthenticationContext ac = new AuthenticationContext(user, pass.toCharArray(), null);
            Session session = connection.authenticate(ac);
            try (DiskShare share = (DiskShare) session.connectShare(path)) {
                for (FileIdBothDirectoryInformation f : share.list("", suffix)) {
                    FileTime changeTime = f.getLastWriteTime();
                    long windowsTimestamp = changeTime.toEpochMillis();
                    Instant instant = Instant.ofEpochMilli(windowsTimestamp);
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                    if (dateTime.isAfter(localDateTime)) {
                        log.info("File : {},Change Time : {}, 跳過", f.getFileName(), localDateTime);
                        continue;
                    }
                    log.info("File : {},Change Time : {}", f.getFileName(), localDateTime);
                    String fileUrl = f.getFileName();
                    File smbFileRead = share.openFile(fileUrl, EnumSet.of(AccessMask.GENERIC_READ), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null);
                    InputStream in = smbFileRead.getInputStream();
                    ClassExecuteServiceFactory.getFileReadStrategy(code).handleFileRead(in, info);
                    log.info("File : {} read success", fileUrl);
                }
            }
        } catch (Exception e) {
            log.error("Error reading file from SMB: {}", e.getMessage(), e);
        }

    }

}

五、總結

通過本文,我們了解了如何在Spring Boot應用中讀取Windows共享文件。我們使用了jcifs庫來處理SMB協(xié)議,并通過配置類、服務類和控制器類實現(xiàn)了文件的讀取功能,希望這篇文章對你有所幫助。

以上就是使用SpringBoot讀取Windows共享文件的代碼示例的詳細內(nèi)容,更多關于SpringBoot讀取Windows共享文件的資料請關注腳本之家其它相關文章!

相關文章

最新評論

象山县| 札达县| 桐柏县| 特克斯县| 阿坝| 镇平县| 黔南| 宜宾县| 乐东| 通山县| 开平市| 淮北市| 芜湖县| 苗栗县| 新密市| 文化| 永顺县| 陆丰市| 美姑县| 莫力| 安图县| 成安县| 谢通门县| 房产| 金沙县| 灵璧县| 鄂温| 宁都县| 耿马| 阿拉尔市| 克东县| 佛冈县| 台东市| 崇州市| 临澧县| 青海省| 高密市| 夏邑县| 丹阳市| 温州市| 汝州市|