JAVA FTP 客户端 .
- private FTPClient connectFtp(){
- FTPClient ftp = null;
- String user = "";
- String password = "";
- String server = "";
- int port = "21";
- String root = "/";
- ftp=new FTPClient();
- ftp.addProtocolCommandListener(new ProtocolCommandListener() {
- String message = "";
- public void protocolCommandSent(ProtocolCommandEvent event) {
- message = event.getMessage();
- if ("pass".equalsIgnoreCase(event.getCommand())) {
- // 隐藏密码
- message = message.substring(0, message.indexOf(" ")) + " ******";
- }
- System.out.println(message);
- }
- public void protocolReplyReceived(ProtocolCommandEvent event) {
- System.out.println(event.getMessage());
- }
- });
- try {
- int reply;
- ftp.connect(server, port);
- reply = ftp.getReplyCode();
- System.out.println("reply code: "+reply);
- String msg;
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- msg="FTP服务器拒绝访问";
- System.out.println(msg);
- }
- if (!ftp.login(user, password)) {
- ftp.logout();
- msg="用户名或者密码错误";
- System.out.println(msg);
- }
- //设置ftp的工作目录
- String[] folders = root.split("/");
- for (int i = 0; i < folders.length; i++) {
- String folder=folders[i];
- if(folder.trim().length()==0)
- continue;
- if (!ftp.changeWorkingDirectory(folder)) {
- if (ftp.makeDirectory(folder)) {
- if (!ftp.changeWorkingDirectory(folder)) {
- msg="不能转到" + folder + "目录";
- System.out.println(msg);
- }
- } else {
- msg="不能在ftp服务器上建立" + folder + "目录";
- System.out.println(msg);
- }
- }
- }
- System.out.println("Current working directory: "+ftp.printWorkingDirectory());
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("connectFtp发生异常"+ e.getMessage());
- disconnectFtp(ftp);
- }
- return ftp;
- }
- private void disconnectFtp(FTPClient ftp ){
- if(ftp!=null && ftp.isConnected()){
- try {
- ftp.disconnect();
- } catch (IOException e) {
- }
- }
- }
- private void uploadFile(File file, String fileAlias,FTPClient ftp) {
- String filename=fileAlias;
- try {
- filename = new String(filename.getBytes(), "iso8859_1");
- } catch (UnsupportedEncodingException e) {
- filename=fileAlias;
- }
- InputStream istream=null;
- try {
- String msg;
- System.out.println("Working Directory: "+ftp.printWorkingDirectory());
- ftp.setFileType(FTP.BINARY_FILE_TYPE);
- ftp.setControlEncoding("GBK");
- istream = new FileInputStream(file);
- ftp.storeFile(filename, istream);
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("uploadFile()发生异常"+ e.getMessage());
- } finally {
- if(istream!=null)
- try {
- istream.close();
- } catch (IOException e1) {
- }
- }
posted on 2012-11-12 22:50 anuo_ruibo 阅读(587) 评论(0) 编辑 收藏 举报