public String download(String ftpUrl,String sfzh){ //ftpUrl :文件夾路徑 afzh:圖片路徑 FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; String re=null; try { ftpClient.connect(ftp_ip,ftp_port);//ip地址,端口號 ftpClient.login(ftp_username, ftp_password);//賬戶,密碼 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //是否成功登錄服務器 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } //跳轉到指定目錄 ftpClient.changeWorkingDirectory(ftpUrl); //5.遍歷下載的目錄 FTPFile[] fs = ftpClient.listFiles(); for (FTPFile ff : fs){ //解決中文亂碼問題,兩次解碼 byte[] bytes=ff.getName().getBytes("iso-8859-1"); String fileName=new String(bytes,"utf-8"); if(sfzh.equals(fileName)){ inputStream = ftpClient.retrieveFileStream(fileName); } } if (inputStream != null) { byte[] data=null; ByteArrayOutputStream outStream =new ByteArrayOutputStream(); data=new byte[inputStream.available()]; int len=0; while((len=inputStream.read(data))!=-1){ outStream.write(data,0,len); } data=outStream.toByteArray(); Encoder encoder=Base64.getEncoder(); re=encoder.encodeToString(data); } } catch (Exception e) { e.printStackTrace(); }finally{ if(ftpClient.isConnected()){ try{ ftpClient.disconnect(); }catch(IOException e){ e.printStackTrace(); } } if(null != inputStream){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return re; }
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>