在指定ftp上建立文件

public static void uploadFile(String str) {
		
		Date date = new Date();
		
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String time=dateFormat.format(date);
		Connection baseConn = null;
		PreparedStatement geneIdPst = null;
		ResultSet rs = null;

 		String fileName = time+".txt";// 创建的文件

 		FTPClient ftpClient = new FTPClient();
 		try {
 			baseConn = ServiceManager.getSession().getNewConnection("base");
 			String cfgIdSQL = "SELECT HOST_IP,USERNAME,PASSWORD,remote_path  FROM BASE.bs_ftp t,base.bs_ftp_path m where t.FTP_CODE='KEEP_MSG_UPLOAD' and t.FTP_CODE=m.FTP_CODE";
			geneIdPst = baseConn.prepareStatement(cfgIdSQL);
			rs = geneIdPst.executeQuery();
			rs.next();
			String userPassword =rs.getString(3);// ftp登录密码 Ftpuser-123
			String userName = rs.getString(2);// ftp登录用户名 ftpuser
			String server = rs.getString(1);// ftp地址 10.10.108.45
			String path = rs.getString(4);// 指定写入的目录/outerPloy/ftp/sms/
            InputStream is = null;
 		    
 			is = new ByteArrayInputStream(str.getBytes());//输入流
 			
 		    ftpClient.connect(server);//连接服务器
 			
 			if(ftpClient.login(userName, userPassword)){//登录ftp
 				ftpClient.changeWorkingDirectory(path);//指定写入的目录
 				
 				FTPFile[] files = ftpClient.listFiles(path); 
 	 			
 				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//写操作
 	 			
 				ftpClient.storeFile(new String(fileName.getBytes("utf-8"),
 	 					"iso-8859-1"), is);
 			}
 			is.close();
 		} catch (Exception e) {
 			e.printStackTrace();
 		} finally {
 			if (ftpClient.isConnected()) {
 				try {
 					ftpClient.disconnect();
 				} catch (Exception e) {
 					e.printStackTrace();
 				}
 			}
 		}
 	}

 

你可能感兴趣的:(ftp)