//ftp构造 public FTPUtil(String hostname, int port, String userName, String password) { ftpClient = new FTPClient(); this.hostname = hostname; this.port = port; this.userName = userName; this.password = password; }
//ftp连接 public boolean connectServer() throws SocketException, IOException { ftpClient.connect(hostname, port); boolean isLogin = ftpClient.login(userName, password); boolean isSetFileType = ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.cwd(rootNode); ftpClient.enterLocalPassiveMode(); return isLogin && isSetFileType; }
ftp下载文件
public String downloadFileFromFTP(String ftpFilePath) { InputStream is = null; byte[] data = null; ByteArrayOutputStream swapStream = null; try { // 获取ftp上的文件流 is = ftpClient.retrieveFileStream(new String(ftpFilePath.getBytes("GBK"),"ISO-8859-1")); swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int rev = 0; while ((rev = is.read(buff, 0, buff.length)) > 0) { swapStream.write(buff, 0, rev); } data = swapStream.toByteArray(); ftpClient.completePendingCommand(); logger.info("FTP文件下载成功!"); } catch (Exception e) { logger.error("FTP文件下载失败!", e); } finally { try { if (is != null) { is.close(); } if (swapStream != null) { swapStream.close(); } } catch (IOException e) { logger.info("关闭流发生异常_"+e); } } return Base64.encodeBase64String(data);
//上传文件
public boolean uploadFile(File localFile, String remoteFile) throws IOException { FileInputStream is = null; try { is = new FileInputStream(localFile); logger.info("FileInputStream file" + is); return ftpClient.appendFile(remoteFile, is); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } }