public void uploadFile(String filePath, byte[] data) throws IOException { login(); OutputStream os = ftpClient.storeFileStream(filePath); int ftpUploadReplyCode = ftpClient.getReplyCode(); if (FTPReply.isNegativePermanent(ftpUploadReplyCode)) { throw new IOException("SERVER FTP:REQUEST DENIED"); } else if (FTPReply.isNegativeTransient(ftpUploadReplyCode)) { uploadFile(filePath, data); } ByteArrayInputStream bais = new ByteArrayInputStream(data); IOUtils.copy(bais, os); bais.close(); os.flush(); os.close(); if (!ftpClient.completePendingCommand()) { uploadFile(filePath, data); } logout(); }
/** * Download a file from the server * * @param fileName * @param isTextFile * @return */ public boolean getFile(String remoteFileName, String localFileName, boolean isTextFile) throws FtpException { byte[] data = new byte[BUFFER]; int count; File tmpFile = new File(localFileName.substring(0, localFileName.lastIndexOf(File.separatorChar))); if (!tmpFile.exists()) { tmpFile.mkdirs(); } try { if (isTextFile) { ftp.setFileType(FTPClient.ASCII_FILE_TYPE); } else { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); } boolean isValidWrt = ftp.retrieveFile( remoteFileName, new BufferedOutputStream(new FileOutputStream(localFileName))); if (!isValidWrt) { close(); throw new FtpException("remote file or local file is not exist !"); } InputStream ftpReader = ftp.retrieveFileStream(remoteFileName); if (ftpReader == null) { throw new FtpException("no file"); } BufferedInputStream downloadFileIn = new BufferedInputStream(ftpReader, BUFFER); BufferedOutputStream downloadFileOut = new BufferedOutputStream(new FileOutputStream(localFileName), BUFFER); while ((count = downloadFileIn.read(data, 0, BUFFER)) != -1) { downloadFileOut.write(data, 0, count); downloadFileOut.flush(); } ftpReader.close(); downloadFileIn.close(); downloadFileOut.close(); if (!ftp.completePendingCommand()) { close(); throw new FtpException("remote file or local file is not exist!"); } } catch (Exception ex) { close(); ex.printStackTrace(); logger.info( "\\== ERROR WHILE EXECUTE FTP ==// (File Name:" + remoteFileName + " ==> " + localFileName + ") >>>>>>>>>>>>>" + ex.getLocalizedMessage()); throw new FtpException("ftp file exception:" + ex.getMessage()); } return true; }
/** * Method that downloads a file from the FTP server. * * @param filepath is the absolute path of the file in the FTP server * @return the file content as byte[] * @throws IOException if an i/o error occurs. */ public byte[] downloadFile(String filepath) throws IOException { login(); FTPFile ftpFile = ftpClient.listFiles(filepath)[0]; // file exists on FTP server? if (ftpFile == null) { throw new IOException("NULL FILE POINTER IN THE FTP SERVER"); } // file is a directory? if (ftpFile.isDirectory()) { throw new IOException("FILE POINTER IS A DIRECTORY"); } // its a file and exists. start download stream... InputStream is = ftpClient.retrieveFileStream(filepath); // how the server replied to the fetch command? int ftpReplyCode = ftpClient.getReplyCode(); // denied? if (FTPReply.isNegativePermanent(ftpReplyCode)) { throw new IOException("SERVER FTP:REQUEST DENIED"); // can we try again? } else if (FTPReply.isNegativeTransient(ftpReplyCode)) { // close the already open stream before try again... if (is != null) { is.close(); } return downloadFile(filepath); } // server accepted the command ByteArrayOutputStream baos = new ByteArrayOutputStream(); // copying the file IOUtils.copy(is, baos); // closing open streams is.close(); baos.flush(); baos.close(); // transaction is successful? boolean transactionCompleted = ftpClient.completePendingCommand(); if (!transactionCompleted) { return downloadFile(filepath); } // we got the file logout(); return baos.toByteArray(); }
public static boolean downloadFile(FTPClient ftp, OutputStream output, String filename) throws IOException { // FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码 String isoFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); ftp.retrieveFile(isoFileName, output); if (!ftp.completePendingCommand()) { FTPLogger.error("File transfer failed, file name: " + filename); return false; } return true; }
/** * @param ftp FTP链接 * @param path 目标文件夹路径 * @param filename 待上传文件名 * @param input 输入流 * @return True:上传成功, False:失败 * @throws IOException */ public static boolean uploadFile(FTPClient ftp, String path, String filename, InputStream input) throws IOException { if (!mkdir(ftp, path)) { return false; } // FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码 String isoFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); OutputStream output = ftp.storeFileStream(isoFileName); AttachmentPuller.copy(input, output); if (!ftp.completePendingCommand()) { FTPLogger.error("File transfer failed, file name: " + filename); return false; } return true; }
@Override public void completeTransfer() throws IOException { if (!ftpClient.completePendingCommand()) throw new IOException("non finalized read from FTP server"); }
public static final void main(String[] args) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts; int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; if (args.length < 8) { System.err.println( "Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"); System.exit(1); } server1 = args[0]; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = args[1]; password1 = args[2]; file1 = args[3]; server2 = args[4]; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = args[5]; password2 = args[6]; file2 = args[7]; listener = new PrintCommandListener(new PrintWriter(System.out), true); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { int reply; if (port1 > 0) { ftp1.connect(server1, port1); } else { ftp1.connect(server1); } System.out.println("Connected to " + server1 + "."); reply = ftp1.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp1.disconnect(); System.err.println("FTP server1 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp1.isConnected()) { try { ftp1.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server1."); e.printStackTrace(); System.exit(1); } try { int reply; if (port2 > 0) { ftp2.connect(server2, port2); } else { ftp2.connect(server2); } System.out.println("Connected to " + server2 + "."); reply = ftp2.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp2.disconnect(); System.err.println("FTP server2 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp2.isConnected()) { try { ftp2.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server2."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp1.login(username1, password1)) { System.err.println("Could not login to " + server1); break __main; } if (!ftp2.login(username2, password2)) { System.err.println("Could not login to " + server2); break __main; } // Let's just assume success for now. ftp2.enterRemotePassiveMode(); ftp1.enterRemoteActiveMode( InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort()); // Although you would think the store command should be sent to server2 // first, in reality, ftp servers like wu-ftpd start accepting data // connections right after entering passive mode. Additionally, they // don't even send the positive preliminary reply until after the // transfer is completed (in the case of passive mode transfers). // Therefore, calling store first would hang waiting for a preliminary // reply. if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) { // if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) { // We have to fetch the positive completion reply. ftp1.completePendingCommand(); ftp2.completePendingCommand(); } else { System.err.println("Couldn't initiate transfer. Check that filenames are valid."); break __main; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (ftp1.isConnected()) { ftp1.logout(); ftp1.disconnect(); } } catch (IOException e) { // do nothing } try { if (ftp2.isConnected()) { ftp2.logout(); ftp2.disconnect(); } } catch (IOException e) { // do nothing } } }
/** * 下载批量文件 * * @param remoteFileNameList * @param localFileDirectory * @param tempFileDir * @param isTextFile * @return * @throws FtpException */ public boolean getFile( ArrayList<String> remoteFileNameList, String localFileDirectory, String tempFileDir, boolean isTextFile) throws FtpException { // boolean isValidWrt = false; byte[] data = new byte[BUFFER]; int count; String localFileName = null; String remoteFileName = null; String tempLocalFileDir = localFileDirectory; File tmpFile = new File(localFileDirectory); BufferedInputStream downloadFileIn = null; BufferedOutputStream downloadFileOut = null; if (!tmpFile.exists()) { tmpFile.mkdirs(); } File tempFile = new File(tempFileDir); if (!tempFile.exists()) { tempFile.mkdirs(); } try { // String currPath = ftp.printWorkingDirectory(); if (isTextFile) { ftp.setFileType(FTPClient.ASCII_FILE_TYPE); } else { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); } for (int i = 0; i < remoteFileNameList.size(); i++) { tempLocalFileDir = localFileDirectory; File temp = new File(remoteFileNameList.get(i)); localFileName = temp.getName(); remoteFileName = remoteFileNameList.get(i); if (localFileName.indexOf("(") != -1) { remoteFileName = remoteFileName.substring(0, remoteFileName.indexOf("(")); tempLocalFileDir = tempFileDir; } InputStream ftpReader = ftp.retrieveFileStream(remoteFileName); downloadFileIn = new BufferedInputStream(ftpReader, BUFFER); downloadFileOut = new BufferedOutputStream( new FileOutputStream(tempLocalFileDir + File.separator + localFileName), BUFFER); while ((count = downloadFileIn.read(data, 0, BUFFER)) != -1) { downloadFileOut.write(data, 0, count); downloadFileOut.flush(); } ftpReader.close(); downloadFileIn.close(); downloadFileOut.close(); if (!ftp.completePendingCommand()) { close(); throw new FtpException("remote file or local file is not exist!"); } /* * isValidWrt = ftp.retrieveFile(remoteFileName, new BufferedOutputStream(new * FileOutputStream(tempLocalFileDir + File.separator + localFileName))); if * (!isValidWrt) { throw new FtpException("远程文件不存在或本地文件不存在!"); } */ } } catch (Exception ex) { tmpFile.exists(); logger.info( "\\== ERROR WHILE EXECUTE FTP ==// (File Name:" + remoteFileName + " ==> " + localFileName + ") >>>>>>>>>>>>>" + ex.getLocalizedMessage()); close(); throw new FtpException("ftp file exception:" + ex.getMessage()); } return true; }