ftp

文章目录

1

package com.iss.itreasury.ebank.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.iss.finance.ebank.base.util.ConfigProperties;

public class StvatFtpUtils {

    public StvatFtpUtils() {}

    public static String IP = ConfigProperties.getItem(ConfigProperties.FTP_IP);
    public static String USERNAME = ConfigProperties.getItem(ConfigProperties.FTP_USERNAME);
    public static String PASSWORD = ConfigProperties.getItem(ConfigProperties.FTP_PASSWORD);
    public static String REMOTE_ROOT = ConfigProperties.getItem(ConfigProperties.FTP_REMOTE_ROOT);
    public static String LOCAL_ROOT = ConfigProperties.getItem(ConfigProperties.FTP_LOCAL_ROOT);
    public static String RE_COUNT = ConfigProperties.getItem(ConfigProperties.FTP_RE_COUNT);
    public static String WAIT = ConfigProperties.getItem(ConfigProperties.FTP_WAIT);
    
    public static void sendFiles(File[] files,String date){
    	FTPClient ftp = new FTPClient();
    	try {
            int reply;
            
            ftp.connect(IP);
            System.out.println("Connected to " + IP + ".");

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                throw new RuntimeException("FTP server refused connection.");
            }
            
            if (!ftp.login(USERNAME, PASSWORD))
            {
                ftp.logout();
                throw new RuntimeException("FTP login error.");
            }
            
            System.out.println("Remote system is " + ftp.getSystemName());
            
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            
            ftp.changeWorkingDirectory(REMOTE_ROOT);
            ftp.makeDirectory(date);
            ftp.changeWorkingDirectory(REMOTE_ROOT+"/"+date);
            String wd = REMOTE_ROOT+"/"+date;
            ftp.changeWorkingDirectory(wd);
            
            System.out.println("ftp就绪");
            for (int i = 0; i < files.length; i++) {
            	File f = files[i];
            	InputStream input = new FileInputStream(f);
            	System.out.println("准备传送"+f.getName());
            	ftp.storeFile(wd+"/"+f.getName(), input);
            	System.out.println("传送完毕"+wd+"/"+f.getName());
            	input.close();
			}
            
            System.out.println("上传完成");
            
            ftp.logout();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("FTP EXCEPTION:"+e.getMessage());
		}finally{
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
        }
        
    }
    
    public static String[] downFiles(String date){
    	FTPClient ftp = new FTPClient();
    	try {
            int reply;
            
            ftp.connect(IP);
            System.out.println("Connected to " + IP + ".");

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                throw new RuntimeException("FTP server refused connection.");
            }
            
            if (!ftp.login(USERNAME, PASSWORD))
            {
                ftp.logout();
                throw new RuntimeException("FTP login error.");
            }
            
            System.out.println("Remote system is " + ftp.getSystemName());
            
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            
            String wd = REMOTE_ROOT+"/"+date+"/RH";
            boolean flag = ftp.changeWorkingDirectory(wd);
            if(!flag){
            	throw new RuntimeException("融合回执文件未生成");
            }
            
            FTPFile[] ffs =  ftp.listFiles();
            System.out.println("ftp就绪");
            
            String[] paths = new String[1];
            for (int i = 0; i < ffs.length; i++) {
            	File f = new File(StvatFtpUtils.LOCAL_ROOT+"/"+date+"/RH");
            	if(!f.exists()){
            		f.mkdirs();
            	}
            	String path = StvatFtpUtils.LOCAL_ROOT+"/"+date+"/RH/"+ffs[i].getName();
            	OutputStream output = new FileOutputStream(path);
                ftp.retrieveFile(ffs[i].getName(), output);
                output.close();
                paths[0] = path;
			}
            
            System.out.println("下载完成");
            
            ftp.logout();
            
            return paths;
		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException("FTP EXCEPTION:"+e.getMessage());
		}finally{
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
        }
        
    }
    

    /**
     * test
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
    	
    	
    	
    	String ip = "10.10.1.99";
    	String username = "root";
    	String password = "root";
    	
    	FTPClient ftp = new FTPClient();
    	try {
            int reply;
            
            ftp.connect(ip);
            System.out.println("Connected to " + ip + ".");

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                throw new RuntimeException("FTP server refused connection.");
            }
            
            if (!ftp.login(username, password))
            {
                ftp.logout();
                throw new RuntimeException("FTP login error.");
            }
            
            System.out.println("Remote system is " + ftp.getSystemName());
            
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            
            File f1 = new File("C:/Users/issuser/Desktop/aa/");
    		File[] fs = f1.listFiles();
//    		if(fs.length!=7){
//    			//stvat.updateEntryStatus("发送数据给融合异常",2,0);
//    			throw new RuntimeException("本地生成文件数量不正确");
//    		}
    		String date = "20180518";
    		ftp.enterLocalPassiveMode();
            ftp.changeWorkingDirectory("/TAX");
            ftp.makeDirectory(date);
            ftp.changeWorkingDirectory("/TAX/"+date);
            ftp.makeDirectory("HX");
            String wd = "/TAX/"+date+"/HX";
            ftp.changeWorkingDirectory(wd);
            System.out.println("ftp就绪");
            for (int i = 0; i < fs.length; i++) {
            	File f = fs[i];
            	InputStream input = new FileInputStream(f);
            	System.out.println("准备传送"+f.getName());
            	boolean storeFile = ftp.storeFile(new String((wd+"/"+f.getName()).getBytes("utf-8"),"iso-8859-1"), input);
            	System.out.println("传送一次"+wd+"/"+f.getName()+"====返回结果为"+storeFile);
            	if(!storeFile){
            		storeFile = ftp.storeFile(new String((wd+"/"+f.getName()).getBytes("utf-8"),"iso-8859-1"), input);
            		System.out.println("传送两次"+wd+"/"+f.getName()+"====返回结果为"+storeFile);
            	}
            	System.out.println("传送完毕"+wd+"/"+f.getName()+"====返回结果为"+storeFile);
            	input.close();
			}
            
            System.out.println("上传完成");
            
            ftp.logout();
            
            System.out.println("send ftp end.");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("FTP EXCEPTION:"+e.getMessage());
		}finally{
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                	System.out.println("ftp关闭报错:"+f);
                }
            }
        }
        
    }

}

2

package com.iss.framework.util.ftp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.iss.framework.core.bo.BaseBO;
import com.iss.framework.web.tool.SpringUtils;
import com.iss.fs.util.ParameterConstant;

//import sun.net.*;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;

public class FtpUtil implements FtpUtilInterface
{
	
	private int maxBufferSize = 2 * (1024 * 1024);

	private FtpClient ftpClient = null;
	

	/**
	 * connectServer 连接ftp服务器
	 * 
	 * @throws java.io.IOException
	 * @param path
	 *            文件夹,空代表根目录
	 * @param password
	 *            密码
	 * @param user
	 *            登陆用户
	 * @param server
	 *            服务器地址
	 */
	public void connectServer(String path) throws IOException {
		// server:FTP服务器的IP地址;user:登录FTP服务器的用户名
		// password:登录FTP服务器的用户名的口令;path:FTP服务器上的路径
		ftpClient = new FtpClient();
		BaseBO baseBO=(BaseBO)SpringUtils.getBean("baseBO");
		Map FTPParmMap=baseBO.getSysparameterValueByCode(ParameterConstant.FTPSERVER);
		String ftpIP = (String) FTPParmMap.get(ParameterConstant.FTPSERVER_IP);
		String ftpUser =(String) FTPParmMap.get(ParameterConstant.FTPSERVER_USERNAME);
		String ftpPass =(String) FTPParmMap.get(ParameterConstant.FTPSERVER_PASSWORD);
		ftpClient.openServer(ftpIP);
		ftpClient.login(ftpUser, ftpPass);

		ftpClient.cd(path);
		// 用2进制上传、下载
		ftpClient.binary();
	}

	/**
	 * upload 上传文件
	 * 
	 * @throws java.lang.Exception
	 * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
	 * @param fileInput
	 *            上传的文件流
	 * @param filename
	 *            上传的文件
	 */
	public long upload(InputStream fileInput, String newname,String fileName) throws Exception {
		long result = 0;
		OutputStream os = null;

		try {
			os = ftpClient.put(newname);
			byte[] bytes = new byte[maxBufferSize];
			int c;
			while ((c = fileInput.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
		} finally {
			if (fileInput != null) {
				fileInput.close();
			}
			if (os != null) {
				os.close();
			}
		}

		return result;
	}

	/**
	 * download 从ftp下载文件到本地
	 * 
	 * @throws java.lang.Exception
	 * @return
	 * @param newfilename
	 *            本地生成的文件名
	 * @param filename
	 *            服务器上的文件名
	 */
	public void download(String downloadFileName, String showName,HttpServletResponse response) throws Exception {
		InputStream is = null;
		OutputStream out = null;
		try {
			is = ftpClient.get(downloadFileName);

			 response.reset();    
	            response.addHeader("Content-Disposition", "attachment;filename=" + 
	            		URLEncoder.encode(showName, "UTF-8"));
             //得到向客户端输出二进制数据的对象 
	            out = new BufferedOutputStream(response.getOutputStream()); 
			
			if (showName.toUpperCase().indexOf(".DOC") > -1) 
			{
				response.setContentType("application/msword");
			} 
			else	
			{   
                 //设置返回的文件类型
				response.setContentType("application/octet-stream"); 
			}
			 	byte[] bytes = new byte[maxBufferSize];
	            int c;
	            long result = 0;
	            while ((c = is.read(bytes)) != -1) {
	            	out.write(bytes, 0, c);
					result = result + c;
				}
	            
	            response.addHeader("Content-Length", "" + result);
	            out.flush();
			
			
		} finally {
			try
        	{
        		if (is != null)
        		{
        			is.close();
        		}
        		
        		if (out != null)
        		{
        			out.close();
        		}
        	}
        	catch(Exception e)
        	{
        		throw e;
        	}
		}
	}
	
	/** 
	 *  download 
	 *  从ftp下载文件到本地 
	 * @throws java.lang.Exception 
	 * @return  
	 * @param reportFtpClient FTP连接对象
	 * @param ftpFilename ftp上保存的文件名 
	 * @param newfilename 下载到服务器上的文件名 
	 */
	public long downloadReport(String ftpFilename, String newfilename) throws Exception {
		long result = 0;
		InputStream is = null;
		FileOutputStream os = null;
		try {
			is = ftpClient.get(ftpFilename);
			File outfile = new File(newfilename);
			os = new FileOutputStream(outfile);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
				result = result + c;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
		return result;
	}
	
	/**
	 * delete ftp上的文件
	 * 
	 * @throws java.lang.Exception
	 * @return
	 * @param newfilename
	 *            本地生成的文件名
	 * @param filename
	 *            服务器上的文件名
	 */
	public void delete(String downloadFileName) throws Exception {
		ftpClient.sendServer("DELE "+downloadFileName+ "\r\n");
	}

	/**
	 * closeServer 断开与ftp服务器的链接
	 * 
	 * @throws java.io.IOException
	 */
	public void closeServer() throws IOException {
		if (ftpClient != null) {
			ftpClient.closeServer();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值