java operating ftp Upload Files

Some time ago wrote a demand synchronization information ftp, means that the synchronization information iptv equipment of our project timing to generate a csv file and upload it to the other side of the ftp server. The first time you do this demand, operating with java ftp server, ftp server, including connection to log the contents written to a file and uploaded to the ftp server, and finally disconnected.
Synchronization information bean

public class FtpIptvBean {
    private  String region ;//所属分公司
    private  String stbid;//机顶盒标识 终端SN号
    private String deviceVendorName;//设备厂商
    private String terminalModel;//终端型号
    private String mangerDate;//设备入库时间 yyyyMMddHHmmss
    private String  attribution;//政企/家客 在设备表中用type表示  1是家客,2 是政企(集客)
    //setter/getter
}

Information synchronization classes TerminalTestTask

//导入与ftp相关的包
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

//io流相关的包
import java.io.*;

public class TerminalTestTask {
    private FTPClient ftpClient = null;
    
    File file = new File(fileName);
    //创建文件
    FtpConnetUtil.createFile(file);
    //需要写入文件的内容
    List<FtpIptvBean> contentList=terminalTestTaskService.selectIptvInfo();
    
    //省略for循环解析,将要存入文件的字段拼接起来
     String contentStr =contentList.get(i).getRegion()+"|"+contentList.get(i).getStbid()+"|"+contentList.get(i).getTerminalModel()+"|"+contentList.get(i).getDeviceVendorName()+"|"+intime+"|"+attribution;
    //向文件中写入内容并且换行
    FtpConnetUtil.fileChaseFWNewLine(fileName, contentStr);
    
    //通过配置文件读取ftp有关配置信息
    Properties properties = FtpConnetUtil.getConnet();
        String ftpurl = properties.getProperty("ftpiptvurl");
        String ftpport = properties.getProperty("ftpiptvport");
        String ftpusername = properties.getProperty("ftpiptvusername");
        String ftppassword = properties.getProperty("ftpiptvpassword");
        //服务器文件地址
        String ftppath = properties.getProperty("ftpiptvpath");
    //创建一个FTPClient 对象
    ftpClient = new FTPClient();
    //连接ftp
    ftpClient.connect(ftpurl,Integer.parseInt(ftpport));
    //登录ftp服务器
    ftpClient.login(ftpusername, ftppassword);
    //创建文件输入流
    FileInputStream input = null;
    
    //在ftp服务器上新建一个目录用于存放上传的文件
    ftpClient.makeDirectory(ftppath);
    //修改当前工作目录
    ftpClient.changeWorkingDirectory(ftppath);
    
    /*调用FTPClient.enterLocalPassiveMode();这个方法采用的是被动模式连接,就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据。*/
     ftpClient.enterLocalPassiveMode();
     // FTP的传输有两种方式:ASCII传输模式和二进制数据传输模式。
     ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
     //把文件内容写入流中
     input = new FileInputStream(file);
     //将流写入服务器
     flag = ftpClient.storeFile(file.getName(), input);
     //文件上传到ftp服务器之后就断开连接退出
     ftpClient.logout();
    
    //执行关闭流操作
}

Involved ftp tools

public class FtpConnetUtil {
    
    /**
     * 创建文件
     * @param fileName
     * @return
     */
    public static boolean createFile(File fileName)throws Exception{
        try{
            if(!fileName.exists()){
                fileName.createNewFile();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return true;
    }
    
     /**
     * 写入文件,追加写入并且换行
     * @param filePath
     * @param content
     */
    public static void fileChaseFWNewLine(String filePath, String content) {
        try {
            //构造函数中的第二个参数true表示以追加形式写文件
            FileWriter fw = new FileWriter(filePath,true);
            fw.write(content);
            fw.write("\r\n"); //表示换行
            fw.close();
        } catch (IOException e) {
            System.out.println("文件写入失败!" + e);
        }
    }
    //读取配置文件
    public static Properties getConnet() throws Exception{
        Properties properties = new Properties();
        InputStream is = FtpConnetUtil.class.getResourceAsStream("ftp.properties");
        properties.load(is);
        is.close();
        return properties;
    }
    
    
    /**
     * 获取FTPClient对象
     * @param ftpHost FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort FTP端口 默认为21    
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }
    
}

Summary: The
mode of connection ftp: passive mode and active mode, and the mode of java ftp connection setup problems.

(1) PORT (active mode)
principle PORT Chinese called active mode works: When an FTP client to connect to FTP server port 21, and sends the user name and password, the login is successful for a list or a list of reading data, the client randomized, open a port (above 1024), sends a pORT command to the FTP server, the server tells the client using active mode and an open port; pORT FTP server receives an active mode command and the port number, and port of the server 20 by the client open port connection, data transmission.

(2) PASV (passive mode)
PASV is an acronym for Passive and Chinese passive mode, the working principle: FTP client to connect to FTP server port 21, and sends the user name and password, the login is successful for a list or a list of read data when sending PASV command to the FTP server, a randomized, open port (1024 or more) locally, then the open port telling the client, then the client server connected to an open port for data transmission.
(3) compare the two modes of
the active mode: the client to the server with an open port; passive mode: the server to the client with an open port. As many client ports within the firewall, open ports on the server side with the more difficult. So more time with passive mode.
(4) java, a network with a passive mode, the active mode with the external network link.

FTPClient ftpClient = new FTPClient();
ftpClient.connect(url, port);
//主动模式
//ftpClient.enterLocalActiveMode(); 
ftpClient.enterLocalPassiveMode(); //被动模式
ftpClient.setControlEncoding("UTF-8");
ftpClient.changeWorkingDirectory(path);

Reference Bowen: HTTPS: //www.cnblogs.com/huhaoshida/p/5412615.html
https://blog.csdn.net/weixin_44706512/article/details/89281792
https://blog.csdn.net/afei3418/article / the Details / 54,375,858
(Chinese garbled) https://blog.csdn.net/liquantong/article/details/74080095

Guess you like

Origin www.cnblogs.com/jasonboren/p/12104580.html