private static void ftpCreateDirectoryTree(FTPClient client, String dirTree) throws IOException { boolean dirExists = true; // tokenize the string and attempt to change into each directory level. // If you cannot, then start creating. String[] directories = dirTree.split("/"); for (String dir : directories) { if (!dir.isEmpty()) { if (dirExists) { dirExists = client.changeWorkingDirectory(dir); } if (!dirExists) { if (!client.makeDirectory(dir)) { throw new IOException( "Unable to create remote directory '" + dir + "'. error='" + client.getReplyString() + "'"); } if (!client.changeWorkingDirectory(dir)) { throw new IOException( "Unable to change into newly created remote directory '" + dir + "'. error='" + client.getReplyString() + "'"); } } } } }
/** * Description: 向FTP服务器上传文件 * * @param host FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param basePath FTP服务器基础目录 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回true,否则返回false */ public static boolean uploadFile( String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input) { boolean result = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(host, port); // 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 ftp.login(username, password); // 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; } // 切换到上传目录 if (!ftp.changeWorkingDirectory(basePath + filePath)) { // 如果目录不存在创建目录 String[] dirs = filePath.split("/"); String tempPath = basePath; for (String dir : dirs) { if (null == dir || "".equals(dir)) continue; tempPath += "/" + dir; if (!ftp.changeWorkingDirectory(tempPath)) { if (!ftp.makeDirectory(tempPath)) { return result; } else { ftp.changeWorkingDirectory(tempPath); } } } } // 设置上传文件的类型为二进制类型 ftp.setFileType(FTP.BINARY_FILE_TYPE); // 上传文件 if (!ftp.storeFile(filename, input)) { return result; } input.close(); ftp.logout(); result = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return result; }
public void writeTempFile(String fileName, String sessionId, InputStream is) throws FTPException { FTPClient ftp = connect(); try { ftp.makeDirectory("temp"); ftp.changeWorkingDirectory("temp"); ftp.makeDirectory(sessionId); ftp.changeWorkingDirectory(sessionId); ftp.storeFile(fileName, is); ftp.logout(); } catch (IOException e) { LOGGER.error("Could not write tempfile " + fileName, e); } finally { try { ftp.disconnect(); } catch (IOException e) { // Empty... } } }
/** * * * <pre> * <b>Description:</b> * Function create ftp folder * <b>Creation date: </b>02.05.08 * <b>Modification date: </b>02.05.08 * </pre> * * @param String sDirName � directory name * @author Vitalii Fedorets * @return boolean � true if success */ public boolean createFolder(String sDirName) throws Exception { try { FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirName); if (!oFtp.makeDirectory(sDirName)) { log.setError("Could not create directory `" + sDirName + "`"); oFtp.disconnect(); return false; } oFtp.disconnect(); return true; } catch (Exception oEx) { throw oEx; } }
/** * Convenience method, so that we don't open a new connection when using this method from within * another method. Otherwise every API invocation incurs the overhead of opening/closing a TCP * connection. */ private boolean mkdirs(FTPClient client, Path file, FsPermission permission) throws IOException { boolean created = true; Path workDir = new Path(client.printWorkingDirectory()); Path absolute = makeAbsolute(workDir, file); String pathName = absolute.getName(); if (!exists(client, absolute)) { Path parent = absolute.getParent(); created = (parent == null || mkdirs(client, parent, FsPermission.getDefault())); if (created) { String parentDir = parent.toUri().getPath(); client.changeWorkingDirectory(parentDir); created = created & client.makeDirectory(pathName); } } else if (isFile(client, absolute)) { throw new IOException( String.format("Can't make directory for path %s since it is a file.", absolute)); } return created; }
public void mkDir(String pathName) throws FtpException { try { String currPath = ftp.printWorkingDirectory(); // if ( !currPath.equals(pathName.substring(0, currPath.length() ) ) // ) // throw new FtpException("目录错"); String newPath = pathName; StringTokenizer newPaths = new StringTokenizer(newPath, "/"); while (newPaths.hasMoreTokens()) { currPath = newPaths.nextToken().trim(); ftp.makeDirectory(currPath); ftp.changeWorkingDirectory(currPath); } } catch (Exception ex) { close(); throw new FtpException(ex.getMessage()); } }
public String showDirectories() { String valores = "_root/"; try { // Con esto podemos cambiar la carpeta actual cliente.changeWorkingDirectory("/Musica/Megadeth"); cliente.makeDirectory("Killing Is My Business"); System.out.println("La ruta actual es: " + cliente.printWorkingDirectory()); // Con esto podemos obtener los directorios de la carpeta actual FTPFile[] directorios = cliente.listDirectories(); for (int i = 0; i < directorios.length; i++) { valores += directorios[i].getName() + "/"; } // Con esto podemos volver al directorio raíz cliente.changeToParentDirectory(); System.out.println("La ruta nueva es es: " + cliente.printWorkingDirectory()); } catch (IOException err) { valores = "El error es: " + err.getMessage(); } return valores; }
public boolean makeFtpFile(String host, int port, String username, String pwd, String filepath) { FTPClient ftpClient = new FTPClient(); boolean flag = false; try { ftpClient.connect(host, port); } catch (SocketException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } ftpClient.setControlEncoding("utf-8"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); System.out.println("返回码:" + ftpClient.getReplyCode()); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { try { if (ftpClient.login(username, pwd)) { try { String str = new String(filepath); flag = ftpClient.makeDirectory(new String(str.getBytes("GBK"), "iso-8859-1")); System.out.println("ftp创建文件夹:" + flag); ftpClient.changeWorkingDirectory(str); } catch (IOException e) { System.out.println("连接FTP出错:" + e.getMessage()); } } } catch (IOException e) { e.printStackTrace(); } } try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } return flag; }
protected void process() { String actPath = getParameter("actPath"); if ((actPath == null) || (actPath.trim().length() == 0)) { actPath = getCwd(); } if (!this.checkAccess(actPath)) { return; } String ftpServerName = getParameter("ftpServerName"); if (ftpServerName == null) { ftpParamForm(null); return; } StringBuffer alertText = new StringBuffer(); if (ftpServerName.trim().length() == 0) { alertText.append( getResource("alert.missingFtpServer", "FTP Server is a required field") + "\\n"); } String userid = getParameter("userid"); if (userid.trim().length() == 0) { alertText.append(getResource("alert.missingFtpUserid", "Userid is a required field") + "\\n"); } String password = getParameter("password"); if (password.trim().length() == 0) { alertText.append( getResource("alert.missingFtpPassword", "Password is a required field") + "\\n"); } String remoteDir = getParameter("remoteDir"); if (alertText.length() > 0) { ftpParamForm(alertText.toString()); return; } output.println("<HTML>"); output.println("<HEAD>"); output.println( "<link rel=\"stylesheet\" type=\"text/css\" href=\"/webfilesys/styles/common.css\">"); output.println( "<link rel=\"stylesheet\" type=\"text/css\" href=\"/webfilesys/styles/skins/" + userMgr.getCSS(uid) + ".css\">"); output.println("</HEAD>"); output.println("<BODY>"); headLine(getResource("label.ftpBackupHead", "Backup to FTP Server")); output.println("<br>"); output.println("<form accept-charset=\"utf-8\" name=\"form1\">"); output.println("<table class=\"dataForm\" width=\"100%\">"); output.println("<tr><td class=\"formParm1\">"); output.println(getResource("label.ftpServerName", "Name or IP of FTP server") + ":"); output.println("</td>"); output.println("<td class=\"formParm2\">"); output.println(ftpServerName); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm1\">"); output.println(getResource("label.ftpLocalDir", "Local Folder to backup") + ":"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm2\">"); output.println(CommonUtils.shortName(getHeadlinePath(actPath), 70)); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm1\">"); output.println(getResource("label.currentcopy", "current file") + ":"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm2\">"); output.println("<span id=\"currentFile\"/>"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm1\">"); output.println(getResource("label.xferStatus", "transferred") + ":"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm2\">"); output.println("<span id=\"xferStatus\"/>"); output.println("</td></tr>"); output.println("</table>"); output.println("</form>"); String subDir = null; int lastSepIdx = actPath.lastIndexOf(File.separator); if ((lastSepIdx >= 0) && (lastSepIdx < (actPath.length() - 1))) { subDir = actPath.substring(lastSepIdx + 1); } boolean recursive = (getParameter("recursive") != null); FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(ftpServerName); Logger.getLogger(getClass()) .debug("FTP connect to " + ftpServerName + " response: " + ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftpClient.login(userid, password)) { ftpClient.setFileType(FTP.IMAGE_FILE_TYPE); if ((remoteDir.trim().length() > 0) && (!ftpClient.changeWorkingDirectory(remoteDir))) { javascriptAlert("FTP remote directory " + remoteDir + " does not exist!"); } else { boolean remoteChdirOk = true; if (!ftpClient.changeWorkingDirectory(subDir)) { if (!ftpClient.makeDirectory(subDir)) { Logger.getLogger(getClass()).warn("FTP cannot create remote directory " + subDir); remoteChdirOk = false; } else { Logger.getLogger(getClass()).debug("FTP created new remote directory " + subDir); if (!ftpClient.changeWorkingDirectory(subDir)) { Logger.getLogger(getClass()) .warn("FTP cannot chdir to remote directory " + subDir); remoteChdirOk = false; } } } if (remoteChdirOk) { if (!backupDir(ftpClient, actPath, recursive, output)) { javascriptAlert("FTP backup failed"); } else { output.println("<script language=\"javascript\">"); output.println("document.getElementById('currentFile').innerHTML='';"); output.println("</script>"); } } else { javascriptAlert("FTP cannot create remote subdirectory " + subDir); } } } else { Logger.getLogger(getClass()).info("FTP connect to " + ftpServerName + " login failed"); javascriptAlert("Login to FTP server " + ftpServerName + " failed"); } } else { Logger.getLogger(getClass()) .warn("FTP connect to " + ftpServerName + " response: " + reply); javascriptAlert("Login to FTP server " + ftpServerName + " failed"); } ftpClient.logout(); ftpClient.disconnect(); // output.println("<br>" + filesTransferred + " files (" + bytesTransferred / 1024 + " KB) // transferred"); } catch (SocketException sockEx) { Logger.getLogger(getClass()).warn(sockEx); javascriptAlert("FTP transfer failed: " + sockEx); } catch (IOException ioEx) { Logger.getLogger(getClass()).warn(ioEx); javascriptAlert("FTP transfer failed: " + ioEx); } output.println( "<center><FORM><INPUT type=\"Button\" VALUE=\"" + getResource("button.closewin", "Close Window") + "\" onClick=\"self.close()\"></FORM></center>"); output.flush(); }
private boolean backupDir( FTPClient ftpClient, String localPath, boolean recursive, PrintWriter output) throws IOException { boolean error = false; File localDirFile = new File(localPath); if (localDirFile.isDirectory() && (localDirFile.canRead())) { File localFileList[] = localDirFile.listFiles(); if (localFileList != null) { for (int i = 0; i < localFileList.length; i++) { File localFile = localFileList[i]; if (localFile.isDirectory()) { if (recursive) { String subDir = localFile.getName(); String localPathChild = null; if (localPath.endsWith(File.separator)) { localPathChild = localPath + subDir; } else { localPathChild = localPath + File.separator + subDir; } boolean remoteChdirOk = true; if (!ftpClient.changeWorkingDirectory(subDir)) { if (!ftpClient.makeDirectory(subDir)) { Logger.getLogger(getClass()).warn("FTP cannot create remote directory " + subDir); remoteChdirOk = false; } else { Logger.getLogger(getClass()).debug("FTP created new remote directory " + subDir); if (!ftpClient.changeWorkingDirectory(subDir)) { Logger.getLogger(getClass()) .warn("FTP cannot chdir to remote directory " + subDir); remoteChdirOk = false; } } } if (remoteChdirOk) { if (!backupDir(ftpClient, localPathChild, recursive, output)) { error = true; } if (!ftpClient.changeWorkingDirectory("..")) { Logger.getLogger(getClass()).warn("FTP cannot chdir .. from " + subDir); return (false); } } else { error = true; } } } else { output.println("<script language=\"javascript\">"); output.println( "document.getElementById('currentFile').innerHTML='" + insertDoubleBackslash( CommonUtils.shortName( localPath.replace('\\', '/') + "/" + localFile.getName(), 64)) + "';"); output.println("</script>"); try { FileInputStream fin = new FileInputStream(localFile); if (!ftpClient.storeFile(localFile.getName(), fin)) { Logger.getLogger(getClass()) .warn("FTP put file " + localPath + "/" + localFile.getName() + " failed"); error = true; } else { Logger.getLogger(getClass()) .debug( "FTP put of file " + localPath + "/" + localFile.getName() + " successful"); filesTransferred++; bytesTransferred += localFile.length(); String temp = filesTransferred + " files (" + numFormat.format(bytesTransferred / 1024) + " KB)"; output.println("<script language=\"javascript\">"); output.println("document.getElementById('xferStatus').innerHTML='" + temp + "';"); output.println("</script>"); } output.flush(); fin.close(); } catch (IOException ioex) { Logger.getLogger(getClass()) .warn( "FTP put file " + localPath + "/" + localFile.getName() + " failed: " + ioex); output.println( "<br>FTP put file " + localPath + "/" + localFile.getName() + " failed: " + ioex); error = true; } } } } } else { Logger.getLogger(getClass()).warn("FTP local directory " + localPath + " is not readable"); return (false); } return (!error); }