往ftp 上写文件

使用sun提供的jar 往ftp上写文件



public class FtpFileManager {
	FtpClient ftpclient;
	Logger log4j=Logger.getLogger(FtpFileManager.class);
	
	private boolean connectServer(){
		String serverName=Constants.getParamVal("ftp.server","");
		String userName=Constants.getParamVal("ftp.user","");
		String password=Constants.getParamVal("ftp.password","");
		int port=21;
		try{
			port=Integer.parseInt(Constants.getParamVal("ftp.port","21"));
		}catch(NumberFormatException e){
			log4j.error("config.properties 文件中,ftp端口必须设置为数字", e);
		}
		try {
			ftpclient=new FtpClient();
			ftpclient.openServer(serverName, port);
			ftpclient.login(userName, password);
			ftpclient.binary();  // 二进制传输
		} catch (IOException e) {
			log4j.error("ftp服务器登陆失败,IP="+serverName+",userName="+userName+"password="+password, e);
			return false;
		}
		
		return true;
		
	}
	
	/**
	 *  往ftp服务器上写文件
	 * @param path
	 * @param filename
	 * @param content
	 * @throws IOException 
	 */
	private void saveFileToServer(String path,String filename,String content) throws IOException{
		TelnetOutputStream out=null;
		InputStream in=null;
		try{
			try{
				ftpclient.cd(path);
			}catch(FileNotFoundException e){
				ftpclient.sendServer("XMKD"+path+"\r\n");  // 新建路径
				ftpclient.readServerResponse();
				ftpclient.cd(path);
			}
			out=ftpclient.put(filename);
			byte[] bytes=content.getBytes();
			in=new ByteArrayInputStream(bytes);
			IOUtils.copy(in, out);
		}catch(Exception e){
			log4j.error("ftp  写文件时异常,文件名:"+filename,e);
		}finally{
			if(in!=null){
				in.close();
			}
			if(out!=null){
				out.close();
			}
		}
		
	}
	
	/**
	 *  文件上传
	 * @param path
	 * @param filename
	 * @param content
	 */
	public void upload(String path,String filename,String content){
		
		try {
			this.connectServer();
			this.saveFileToServer(path, filename, content);
		} catch (IOException e) {
			log4j.error("IO 流关闭异常", e);
		}finally{
			this.logout();
		}
	}
	
	/**
	 *  关闭ftp
	 */
	private void logout(){
		if(ftpclient.serverIsOpen()){
			try {
				ftpclient.closeServer();
			} catch (IOException e) {
				log4j.error("关闭ftp 时异常", e);
			}
		}
	}
	
	public static void main(String[] args) {
		FtpFileManager f=new FtpFileManager();
		f.upload("a", "1.txt", "130");
	}

}

你可能感兴趣的:(log4j,F#,sun)