\\:ip 访问网络上的SMB共享目录、IP接口传输数据、ftp://ip ftp传输

一、访问网络上的SMB共享目录

1.导入JAR包

		<!--访问网络上的SMB共享目录-->
		<dependency>
			<groupId>com.hierynomus</groupId>
			<artifactId>smbj</artifactId>
			<version>0.13.0</version>
		</dependency>

2.使用

            // 定义连接信息
          String username = "Administrator";
          String password = "Password";
          String server = "20.135.22.2";
          String shareName = "TDMRecv";
          String folderPath = "folder";

          SMBClient client = new SMBClient();
          try {
              Connection connection = client.connect(server);
              AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), null);
              Session session = connection.authenticate(ac);
              // 连接到共享
              DiskShare shareFolder = (DiskShare) session.connectShare(shareName);
              // 获取共享目录下的文件列表
              List<FileInfo> files = shareFolder.list(folderPath);
              for (FileInfo file : files) {
                  System.out.println("文件名: " + file.getName());
                  System.out.println("大小: " + file.getSize() + " 字节");
                  System.out.println("是否为目录: " + file.isDirectory());
                  System.out.println("最后修改时间: " + new Date(file.getLastModified()));
                  System.out.println("------------------------");
              }

              // 本地文件夹路径
              File localFolder = new File(String.valueOf(targetFolder));
              // 上传文件夹
              uploadFolder(shareFolder, localFolder ,localFolder);

              FileUtils.deleteDirectory(new File(localFolder.getAbsolutePath()));
          } catch (IOException e) {
              log.error("无法连接到共享或创建文件夹或删除文件失败:" + e.getMessage());
              e.printStackTrace();
          }
private static void uploadFolder(DiskShare shareFolder, File localFolder, File localFolder2) throws IOException {
        if (!localFolder.isDirectory()) {
            log.error("本地文件夹不存在:"+localFolder);
        }
        String localFolderName = "MESRecv\\"+localFolder.getName();
        if (!shareFolder.folderExists(localFolderName)&&localFolder2.getName().equals(localFolder.getName())) {
            // 创建文件夹
            shareFolder.mkdir(localFolderName);
            log.info("文件夹创建成功:" + localFolderName);
        } else {
            log.info("文件夹已存在:" + localFolderName);
        }
        // 遍历本地文件夹
        File[] files = localFolder.listFiles();
        if (files != null) {
            for (File file : files) {
                String remoteFolderPath = "MESRecv\\"+localFolder.getName()+"\\"+file.getName();
                if (file.isDirectory()) {
                    if (!shareFolder.folderExists(remoteFolderPath)) {
                        // 创建文件夹
                        shareFolder.mkdir(remoteFolderPath);
                        uploadFolder(shareFolder, file.getAbsoluteFile(), localFolder2);
                        log.info("文件夹创建成功:"+remoteFolderPath);
                    } else {
                        log.info("文件夹已存在:"+localFolderName);
                    }
                } else {
                    // 上传本地文件到共享目录
                    FileInputStream fis = null;
                    SmbFileOutputStream fos = null;
                    try {
                        File localFile = new File(file.getAbsolutePath());

                        // 上传文件
                        fis = new FileInputStream(localFile);
                        String absolutePath = file.getAbsolutePath();
                        String temporaryFolder = absolutePath.substring(absolutePath.indexOf("temporaryFolder") + "temporaryFolder".length() + 1);
                        String replace = temporaryFolder.replace("\\", "/");
                        String remoteFolderPath1 = "MESRecv/" + replace;
                        String path = "smb://" + shareFolder.getSmbPath().getHostname() + "/" + shareFolder.getSmbPath().getShareName() + "/" + remoteFolderPath1;

                        SmbFile smbFile = new SmbFile(path);
                        fos = new SmbFileOutputStream(smbFile);
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = fis.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                        log.info("文件上传成功:" + file.getAbsolutePath());
                    } finally {
                        IOUtils.closeQuietly(fis);
                        IOUtils.closeQuietly(fos);
                    }
                }
            }
        }
    }

接口传输

1.示例

          String apiUrl = "http://20.135.168.23:8080/test/receive"; // 替换为实际API URL
          String requestData = "{\"key\":\"value\"}"; // 替换为实际请求数据
          log.info("json数据:"+requestData);
            try {
                // 创建URL对象
                URL url = new URL(apiUrl);

                // 打开与URL之间的连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // 设置请求方法为POST
                connection.setRequestMethod("POST");

                // 设置允许输出
                connection.setDoOutput(true);

                // 设置请求头
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

                // 写入请求数据
                DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
                byte[] input = requestData.getBytes();
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();

                // 获取响应码
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    // 打印响应内容
                    log.info("响应内容: " + response.toString());
                } else {
                    log.error("请求失败: HTTP error code: " + responseCode);
                }
                // 关闭连接
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

ftp传输

1.获取文件

        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ip, port);
        // 执行其他初始化操作,例如登录等
        ftpClient.login("administrator", "admin@123");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setControlEncoding("utf-8");
        // 获取最后一个FTP回复的回复代码的整数值。
        int replyCode = ftpClient.getReplyCode();
        // 确定回复代码是否为肯定的完成响应
        if (!FTPReply.isPositiveCompletion(replyCode)) {
             System.out.println("FTP连接失败");
        }
        System.out.println("FTP连接成功");
        // 获取第二级目录中的文件
        FTPFile[] twoFtpFiles = ftpClient.listFiles("/" + DIRNAME);
        for (FTPFile file : twoFtpFiles) {

        }

2.传输文件

        FTPClient ftpClient = new FTPClient();
        ftpClient.connect("20.135.22.2", 21);
        ftpClient.login("Administrator", "Password123");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.changeWorkingDirectory("/MESSJB");
        InputStream inputStream = file.getInputStream();
        ftpClient.storeFile(task.get("commCode").toString()+ ".docx", inputStream);
        inputStream.close();
        ftpClient.logout();
        ftpClient.disconnect();
posted @   chahune  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示