Загрузка данных


public class SmbWriter {

    private final SmbProperties smbProperties;

    public void write(byte[] content, String remoteFileName) {
        SmbProperties.SmbConnection smbConnection = smbProperties.getWrite();
        SmbConfig config = SmbConfig.builder()
                .withDfsEnabled(true)
                .build();
        try (SMBClient client = new SMBClient(config)) {
            try (Connection connection = client.connect(smbConnection.host())) {
                Session session = connection.authenticate(
                        new com.hierynomus.smbj.auth.AuthenticationContext(
                                smbConnection.username(),
                                smbConnection.password().toCharArray(),
                                smbConnection.domain()
                        )
                );

                try (DiskShare share = (DiskShare) session.connectShare(smbConnection.share())) {
                    String fullPath = smbConnection.folder() + "\\" + remoteFileName.replace("/", "\\");
                    String directoryPath = fullPath.substring(0, fullPath.lastIndexOf("\\"));
                    ensureFolderExists(share, directoryPath);

                    try (File file = share.openFile(
                            smbConnection.folder() + "/" + remoteFileName,
                            Set.of(AccessMask.GENERIC_WRITE),
                            null,
                            SMB2ShareAccess.ALL,
                            SMB2CreateDisposition.FILE_OVERWRITE_IF,
                            null
                    )) {
                        try (OutputStream os = file.getOutputStream()) {
                            os.write(content);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private void ensureFolderExists(DiskShare share, String path) {
        String[] folders = path.split("[/\\\\]");
        String current = "";

        for (String folder : folders) {
            if (folder.isBlank()) {
                continue;
            }

            current = current.isEmpty() ? folder : current + "/" + folder;

            if (!share.folderExists(current)) {
                share.mkdir(current);
            }
        }
    }
}