List of usage examples for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE
int BINARY_FILE_TYPE
To view the source code for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE.
Click Source Link
From source file:com.example.lista3new.SyncService.java
private boolean ftpConnect(final String host, final int port, final String username, final String password) { boolean status = false; try {//w w w . j a va2 s .c o m mFTPClient = new FTPClient(); mFTPClient.connect(host, port); if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { status = mFTPClient.login(username, password); mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); Log.d(TAG, "Connected"); } } catch (IOException e) { Log.e(TAG, e.getMessage()); } return status; }
From source file:GridFDock.DataDistribute.java
public Status upload(String local, String remote) throws IOException { ftpClient.enterLocalPassiveMode();//from w ww. ja va 2s . com ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setControlEncoding("GBK"); Status result = null; boolean tmp3 = true; String remoteFileName = remote; if (remote.contains("/")) { remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); if (CreateDirectory(remote, ftpClient) == Status.Create_Directory_Fail) { return Status.Create_Directory_Fail; } } long remoteSize = 0; long localSize = 111111; int i = 0; while (tmp3) { if (remoteSize == localSize) { tmp3 = false; return Status.File_Exits; } else if (remoteSize != localSize) { FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"), "iso-8859-1")); files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"), "iso-8859-1")); if (files.length == 1) { remoteSize = files[0].getSize(); File f = new File(local); localSize = f.length(); result = uploadFile(remoteFileName, f, ftpClient, remoteSize); // System.out.println("********************************** // localSize: "+ // localSize); // System.out.println("********************************** // remoteSize: "+ // remoteSize); if (result == Status.Upload_From_Break_Failed) { if (!ftpClient.deleteFile(remoteFileName)) { return Status.Delete_Remote_Faild; } result = uploadFile(remoteFileName, f, ftpClient, 0); } } else { result = uploadFile(remoteFileName, new File(local), ftpClient, 0); } if (i > 3) { tmp3 = false; } i++; } } return result; }
From source file:com.claim.controller.FileTransferController.java
public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception { FTPClient ftpClient = new FTPClient(); int replyCode; boolean completed = false; try {// ww w . j a v a2 s. com FtpProperties properties = new ResourcesProperties().loadFTPProperties(); try { ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); FtpUtil.showServerReply(ftpClient); } catch (ConnectException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("ConnectException: " + ex.getMessage()); ex.printStackTrace(); } catch (SocketException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("SocketException: " + ex.getMessage()); ex.printStackTrace(); } catch (UnknownHostException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("UnknownHostException: " + ex.getMessage()); ex.printStackTrace(); } replyCode = ftpClient.getReplyCode(); FtpUtil.showServerReply(ftpClient); if (!FTPReply.isPositiveCompletion(replyCode)) { FtpUtil.showServerReply(ftpClient); ftpClient.disconnect(); Console.LOG("Exception in connecting to FTP Serve ", 0); throw new Exception("Exception in connecting to FTP Server"); } else { FtpUtil.showServerReply(ftpClient); Console.LOG("Success in connecting to FTP Serve ", 1); } try { boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); FtpUtil.showServerReply(ftpClient); if (!success) { throw new Exception("Could not login to the FTP server."); } else { Console.LOG("login to the FTP server. Successfully ", 1); } //ftpClient.enterLocalPassiveMode(); } catch (FTPConnectionClosedException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); // APPROACH #2: uploads second file using an OutputStream File files = new File(ftpObj.getFtp_directory_path()); String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator + ftpObj.getFtp_report_type(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType); FtpUtil.showServerReply(ftpClient); String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp); FtpUtil.showServerReply(ftpClient); for (File file : files.listFiles()) { if (file.isFile()) { System.out.println("file ::" + file.getName()); InputStream in = new FileInputStream(file); ftpClient.changeWorkingDirectory(workingDirectoryStmp); completed = ftpClient.storeFile(file.getName(), in); in.close(); Console.LOG( " " + file.getName() + " ", 1); FtpUtil.showServerReply(ftpClient); } } Console.LOG(" ?... ", 1); //completed = ftpClient.completePendingCommand(); FtpUtil.showServerReply(ftpClient); completed = true; ftpClient.disconnect(); } catch (IOException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); ex.printStackTrace(); } } return completed; }
From source file:com.glaf.core.util.FtpUtils.java
/** * /*from ww w . j a v a 2 s. c o m*/ * * @param remoteFile * FTP"/" * @param localFile * */ public static void download(String remoteFile, String localFile) { if (!remoteFile.startsWith("/")) { throw new RuntimeException(" path must start with '/'"); } InputStream in = null; OutputStream out = null; try { if (remoteFile.startsWith("/") && remoteFile.indexOf("/") > 0) { changeToDirectory(remoteFile); remoteFile = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length()); } // ? getFtpClient().enterLocalPassiveMode(); // ? getFtpClient().setFileType(FTP.BINARY_FILE_TYPE); FTPFile[] files = getFtpClient().listFiles(new String(remoteFile.getBytes("GBK"), "ISO-8859-1")); if (files.length != 1) { logger.warn("remote file is not exists"); return; } long lRemoteSize = files[0].getSize(); File file = new File(localFile); out = new FileOutputStream(file); in = getFtpClient().retrieveFileStream(new String(remoteFile.getBytes("GBK"), "ISO-8859-1")); byte[] bytes = new byte[4096]; long step = lRemoteSize / 100; if (step == 0) { step = 1; } long progress = 0; long localSize = 0L; int c; while ((c = in.read(bytes)) != -1) { out.write(bytes, 0, c); localSize += c; long nowProgress = localSize / step; if (nowProgress > progress) { progress = nowProgress; if (progress % 10 == 0) { logger.debug("download progress:" + progress); } } } out.flush(); } catch (Exception ex) { ex.printStackTrace(); logger.error("download error", ex); throw new RuntimeException(ex); } finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } }
From source file:de.aw.awlib.utils.AWRemoteFileServerHandler.java
/** * Uebertraegt ein File auf den Server.// w ww . jav a 2s.c o m * * @param transferFile * das zu uebertragende File. Der Name des File auf dem Server entspriehc dem Namen * dieses Files * @param destDirectoryName * Verzeichnis auf dem Server, in dem das File gespeichert werden soll. */ public void transferFile(final File transferFile, final String destDirectoryName) { new RemoteFileServerTask() { @Override protected ConnectionFailsException doInBackground(Void... params) { FileInputStream fis = null; try { connectClient(); fis = new FileInputStream(transferFile); mClient.changeWorkingDirectory(destDirectoryName); mClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); mClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); if (!mClient.storeFile(transferFile.getName(), fis)) { throw new ConnectionFailsException("Filetransfer failed"); } return null; } catch (IOException e) { return new ConnectionFailsException(mClient); } catch (ConnectionFailsException e) { return e; } finally { disconnectClient(); if (fis != null) { try { fis.close(); } catch (IOException e) { //TODO Execption bearbeiten e.printStackTrace(); } } } } }.execute(); }
From source file:com.rvl.android.getnzb.LocalNZB.java
public void uploadLocalFileFTP(String filename) { UPLOADFILENAME = filename;/*www .ja v a 2s . c o m*/ UPLOADDIALOG = ProgressDialog.show(this, "Please wait...", "Uploading '" + filename + "' to FTP server."); SharedPreferences prefs = GetNZB.preferences; if (prefs.getString("FTPHostname", "") == "") { uploadDialogHandler.sendEmptyMessage(0); Toast.makeText(this, "Upload to FTP server not possible. Please check FTP preferences.", Toast.LENGTH_LONG).show(); return; } new Thread() { public void run() { SharedPreferences prefs = GetNZB.preferences; FTPClient ftp = new FTPClient(); String replycode = ""; String FTPHostname = prefs.getString("FTPHostname", ""); String FTPUsername = prefs.getString("FTPUsername", "anonymous"); String FTPPassword = prefs.getString("FTPPassword", "my@email.address"); String FTPPort = prefs.getString("FTPPort", "21"); String FTPUploadPath = prefs.getString("FTPUploadPath", "~/"); if (!FTPUploadPath.matches("$/")) { Log.d(Tags.LOG, "Adding trailing slash"); FTPUploadPath += "/"; } String targetFile = FTPUploadPath + UPLOADFILENAME; try { ftp.connect(FTPHostname, Integer.parseInt(FTPPort)); if (ftp.login(FTPUsername, FTPPassword)) { ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); File file = new File(getFilesDir() + "/" + UPLOADFILENAME); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file)); Log.d(Tags.LOG, "Saving file to:" + targetFile); if (ftp.storeFile(targetFile, buffIn)) { Log.d(Tags.LOG, "FTP: File should be uploaded. Replycode: " + Integer.toString(ftp.getReplyCode())); isUploadedFTP = true; } else { Log.d(Tags.LOG, "FTP: Could not upload file Replycode: " + Integer.toString(ftp.getReplyCode())); FTPErrorCode = Integer.toString(ftp.getReplyCode()); isUploadedFTP = false; } buffIn.close(); ftp.logout(); ftp.disconnect(); } else { Log.d(Tags.LOG, "No ftp login"); } } catch (SocketException e) { Log.d(Tags.LOG, "ftp(): " + e.getMessage()); return; } catch (IOException e) { Log.d(Tags.LOG, "ftp(): " + e.getMessage()); return; } if (isUploadedFTP) { removeLocalNZBFile(UPLOADFILENAME); } UPLOADFILENAME = ""; uploadDialogHandlerFTP.sendEmptyMessage(0); } }.start(); }
From source file:com.radiohitwave.ftpsync.API.java
private void ConnectFTPClient() { Log.info("Connecting to FTP-Server"); try {// w ww. j ava2s. c o m String[] ftpConnection = this.ftpURL.split(":"); this.ftpClient.setAutodetectUTF8(true); this.ftpClient.connect(ftpConnection[0], Integer.parseInt(ftpConnection[1])); this.ftpClient.login(this.GetFTPLoginName(), this.GetFTPLoginPassword()); this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException ex) { Log.error(ex.toString()); Log.remoteError(ex); } }
From source file:com.jaspersoft.jasperserver.api.engine.common.util.impl.FTPUtil.java
private static void putFile(FTPClient ftpClient, String fileName, InputStream inputData) throws Exception { if (ftpClient == null) throw new JSException("Please connect to FTP server first before changing directory!"); if (log.isDebugEnabled()) log.debug("START: FUT FILE = " + fileName); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); boolean state = ftpClient.storeFile(ftpClient.printWorkingDirectory() + "/" + fileName, inputData); if (log.isDebugEnabled()) log.debug("END: FUT FILE = " + fileName + " STATE = " + state); if (!state) { throw new JSException("Fail to upload file " + fileName); }/*from w w w.j a v a 2s.c o m*/ }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * // w ww . jav a 2 s. c om * @throws UnknownHostException * If the hostname cannot be resolved. * * @throws SocketException * If the socket timeout could not be set. * * @throws FTPConnectionClosedException * If the connection is closed by the server. * * @throws LoginFailedException * If the login fails. * * @throws DirectoryChangeFailedException * If changing to the directory provided by the internet * archive fails. * * @throws CopyStreamException * If an I/O error occurs while in the middle of * transferring a file. * * @throws IOException * If an I/O error occurs while sending a command or * receiving a reply from the server * * @throws IllegalStateException * If the contribution object is not ready to upload * (no username, password, server, etc. set) * or if java's xml parser is configured badly */ public void upload() throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException, DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException { final int NUM_XML_FILES = 2; final String META_XML_SUFFIX = "_meta.xml"; final String FILES_XML_SUFFIX = "_files.xml"; final String username = getUsername(); final String password = getPassword(); if (getFtpServer() == null) { throw new IllegalStateException("ftp server not set"); } if (getFtpPath() == null) { throw new IllegalStateException("ftp path not set"); } if (username == null) { throw new IllegalStateException("username not set"); } if (password == null) { throw new IllegalStateException("password not set"); } // calculate total number of files and bytes final String metaXmlString = serializeDocument(getMetaDocument()); final String filesXmlString = serializeDocument(getFilesDocument()); final byte[] metaXmlBytes = metaXmlString.getBytes(); final byte[] filesXmlBytes = filesXmlString.getBytes(); final int metaXmlLength = metaXmlBytes.length; final int filesXmlLength = filesXmlBytes.length; final Collection files = getFiles(); final int totalFiles = NUM_XML_FILES + files.size(); final String[] fileNames = new String[totalFiles]; final long[] fileSizes = new long[totalFiles]; final String metaXmlName = getIdentifier() + META_XML_SUFFIX; fileNames[0] = metaXmlName; fileSizes[0] = metaXmlLength; final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX; fileNames[1] = filesXmlName; fileSizes[1] = filesXmlLength; int j = 2; for (Iterator i = files.iterator(); i.hasNext();) { final File f = (File) i.next(); fileNames[j] = f.getRemoteFileName(); fileSizes[j] = f.getFileSize(); j++; } // init the progress mapping for (int i = 0; i < fileSizes.length; i++) { _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i])); _totalUploadSize += fileSizes[i]; } FTPClient ftp = new FTPClient(); try { // first connect if (isCancelled()) { return; } ftp.enterLocalPassiveMode(); if (isCancelled()) { return; } ftp.connect(getFtpServer()); final int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new RefusedConnectionException(getFtpServer() + "refused FTP connection"); } // now login if (isCancelled()) { return; } if (!ftp.login(username, password)) { throw new LoginFailedException(); } try { // try to change the directory if (!ftp.changeWorkingDirectory(getFtpPath())) { // if changing fails, make the directory if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } // now change directory, if it fails again bail if (isCancelled()) { return; } if (!ftp.changeWorkingDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } } if (isCancelled()) { return; } connected(); // upload xml files uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp); uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp); // now switch to binary mode if (isCancelled()) { return; } ftp.setFileType(FTP.BINARY_FILE_TYPE); // upload contributed files for (final Iterator i = files.iterator(); i.hasNext();) { final File f = (File) i.next(); uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp); } } catch (InterruptedIOException ioe) { // we've been requested to cancel return; } finally { ftp.logout(); // we don't care if logging out fails } } finally { try { ftp.disconnect(); } catch (IOException e) { } // don't care if disconnecting fails } // now tell the Internet Archive that we're done if (isCancelled()) { return; } checkinStarted(); if (isCancelled()) { return; } checkin(); if (isCancelled()) { return; } checkinCompleted(); }
From source file:IHM.FenetreAjoutAffiche.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed try {/*from w w w .j av a2 s . c om*/ FileInputStream input = null; try { input = new FileInputStream(nomF); } catch (FileNotFoundException ex) { Logger.getLogger(FenetreAjoutPhoto.class.getName()).log(Level.SEVERE, null, ex); } FTPSClient ftpClient = new FTPSClient(); ftpClient.connect("iutdoua-samba.univ-lyon1.fr", 990); Properties props = new Properties(); FileInputStream fichier = new FileInputStream("src/info.properties"); props.load(fichier); ftpClient.login(props.getProperty("login"), props.getProperty("password")); System.out.println(ftpClient.getReplyString()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); String remote; remote = "public_html/CPOA/Site/assets/affichesFilm/" + txtNomPhoto.getText(); boolean done = ftpClient.storeFile(remote, input); input.close(); if (done) { System.out.println("reussi"); this.affiche.setNom(txtNomPhoto.getText()); etat = true; this.dispose(); } else { System.out.println(ftpClient.getReplyString()); this.dispose(); } } catch (IOException ex) { Logger.getLogger(FenetreAjoutPhoto.class.getName()).log(Level.SEVERE, null, ex); } }