SoFunction
Updated on 2025-04-05

Example of code for reading shared files in Windows using SpringBoot

1. Background

File sharing is a common requirement in a modern enterprise environment. Windows Shared Folders (SMB/CIFS Protocol) have become the first choice for many enterprises due to their ease of use and extensive compatibility. In Java applications, especially when using the Spring Boot framework, how to read Windows shared files is a topic worth discussing. This article will explain how to implement this feature in Spring Boot applications.

2. Requirements Overview

The project needs to connect to various equipment and instruments, and there are many types, such as serial port transmission, database reading, TCP/IP, etc. There are many solutions, but there are several machines that generate files locally after the experiment. At the beginning, we also had many ideas, such as business personnel conducting import operations every day, and then considering minimizing the operations of business personnel, we thought of a simple way to read the shared files on each machine computer regularly and read the required data files according to its modification time.

3. Preparation: Windows shared folder configuration

A folder has been created and shared in the Windows system, and the network path of the shared folder is recorded, for example: \\ Server name\ Shared folder name.

Make sure the system on which your Spring Boot application is located has access to the shared folder.

The configuration process can be retrieved online, and there are many examples online, let me explain: you can create a shared user separately.
For example username: share password 123456

4. Code examples

4.1 Timely read shared file task Task

@Component
@Slf4j
public class ReadShareFilesTask {

    @Resource
    InspectEquipmentInfoService inspectEquipmentInfoService;

    /**
      *Preliminary execution is now tentatively
      */
    @Scheduled(cron = "0 0 12 * * ?")
    public void executeReadShareFiles() {
        LocalDateTime dateTime = ().minusDays(1);
        List<InspectEquipmentInfo> equipmentInfos = ().eq(InspectEquipmentInfo::getEquipmentType, EquipmentTypeEnum.FILE_SHARING.getCode()).list();
        (equipmentInfo -> {
            try {
                ("Start reading the device:{}, Device name:{}, equipmentip:{}", (), (), ());
                FileReadStrategy fileReadStrategy = (());
                (fileReadStrategy, "Strategy not found");
                ((),dateTime);
            } catch (Exception e) {
                ("读取equipment:{}, Device name:{}, equipmentip:{} fail", (), (), (), e);
            }
        });
    }
}

4.2 Factory category

@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 = ();
        ().forEach(e -> CLASS_CODE_ABSTRACT_CLASS_HANDLE_MAP.putIfAbsent((), e));
    }

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

4.3 File Reading Interface Policy

public interface FileReadStrategy {

    String getCode();

    void listFile(String ip, LocalDateTime dateTime);

    void handleFileRead(InputStream inputStream, InspectEquipmentInfo info);
}

4.4 Policy Implementation Class

@Component
@Slf4j
public class SpectrometerFileReadStrategy implements FileReadStrategy {

    @Resource
    private InspectEquipmentInfoService equipmentInfoService;

    @Resource
    private InspectEquipmentRecordService recordService;

    @Resource
    private ReceiveEquipmentApi receiveEquipmentApi;

    @Override
    public String getCode() {
        return ();
    }

    @Override
    public void listFile(String ip, LocalDateTime dateTime) {
        InspectEquipmentInfo equipmentInfo = ().eq(InspectEquipmentInfo::getEquipmentAddr, ip).one();
        if ((equipmentInfo)) {
            ("The device is not configured in the device table,Device address {}", ip);
            return;
        }
        (equipmentInfo, dateTime);
    }

    @Override
    public void handleFileRead(InputStream inputStream, InspectEquipmentInfo info) {
        try {
            if (inputStream == null) {
                ("ICP spectrometer CSV file cannot be found");
                return;
            }
            //Analyze data based on file flow      }

4.5 Reading shared file flow common class

@Slf4j
public class SmbFileReader {

    public static void listSmbFile(InspectEquipmentInfo info, LocalDateTime dateTime) {
        String path = ();
        String ip = ();
        String user = ();
        String pass = ();
        String suffix = ();
        String code = ();
        SMBClient client = new SMBClient();
        try (Connection connection = (ip)) {
            AuthenticationContext ac = new AuthenticationContext(user, (), null);
            Session session = (ac);
            try (DiskShare share = (DiskShare) (path)) {
                for (FileIdBothDirectoryInformation f : ("", suffix)) {
                    FileTime changeTime = ();
                    long windowsTimestamp = ();
                    Instant instant = (windowsTimestamp);
                    LocalDateTime localDateTime = (instant, ());
                    if ((localDateTime)) {
                        ("File : {},Change Time : {}, jump over", (), localDateTime);
                        continue;
                    }
                    ("File : {},Change Time : {}", (), localDateTime);
                    String fileUrl = ();
                    File smbFileRead = (fileUrl, (AccessMask.GENERIC_READ), null, , SMB2CreateDisposition.FILE_OPEN, null);
                    InputStream in = ();
                    (code).handleFileRead(in, info);
                    ("File : {} read success", fileUrl);
                }
            }
        } catch (Exception e) {
            ("Error reading file from SMB: {}", (), e);
        }

    }

}

5. Summary

Through this article, we understand how toSpring BootRead in the applicationWindowsShare files. We usedjcifsLibrary to handleSMBProtocol, and the file reading function is implemented through configuration classes, service classes and controller classes. I hope this article will be helpful to you.

The above is the detailed content of the code example of using SpringBoot to read Windows shared files. For more information about SpringBoot to read Windows shared files, please follow my other related articles!