List of usage examples for org.apache.commons.net.ftp FTPClient storeFileStream
public OutputStream storeFileStream(String remote) throws IOException
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments *//*from w w w. j av a 2s .co m*/ public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.kcs.core.utilities.FtpUtil.java
public static boolean putFileByStream(String hostname, int port, String username, String password, String remoteFileName, String localFileName) throws Exception { FTPClient ftp = null; boolean result = false; try {/*from ww w.ja v a2 s . co m*/ ftp = FtpUtil.openFtpConnect(hostname, port, username, password); if (null != ftp && ftp.isConnected()) { File localFile = new File(localFileName); InputStream inputStream = new FileInputStream(localFile); System.out.println("Start uploading file"); OutputStream outputStream = ftp.storeFileStream(remoteFileName); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftp.completePendingCommand(); if (completed) { System.out.println("file is uploaded successfully."); result = true; } } } catch (Exception e) { e.printStackTrace(); throw new Exception("Error : " + e.getMessage()); } finally { FtpUtil.closeFtpServer(ftp); } return result; }
From source file:ca.nrc.cadc.web.ServerToServerFTPTransfer.java
public void send(final OutputStreamWrapper outputStreamWrapper, final String filename) throws IOException { final FTPClient ftpClient = connect(); ftpClient.setFileType(FTP.ASCII_FILE_TYPE); ftpClient.enterLocalPassiveMode();/*from w ww. j ava2 s.c o m*/ try { final OutputStream outputStream = ftpClient.storeFileStream(filename); outputStreamWrapper.write(outputStream); outputStream.flush(); outputStream.close(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException f) { // do nothing } } } }
From source file:conf.FTPConf.java
public String subirArchivo(File archivo) { FTPClient ftpClient = new FTPClient(); try {/*from w w w . j a v a2s .c o m*/ ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // APPROACH #2: uploads second file using an OutputStream String serverFile = dir + archivo.getName(); InputStream inputStream = new FileInputStream(archivo); OutputStream outputStream = ftpClient.storeFileStream(serverFile); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftpClient.completePendingCommand(); if (completed) { String link = "ftp://" + user + "@" + server + "/" + serverFile; return link; } } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } return null; }
From source file:ddf.test.itests.catalog.TestFtp.java
private void ftpPutStreaming(FTPClient client, String data, String fileName) throws IOException { LOGGER.info("Start data upload via FTP PUT..."); try (InputStream is = new ByteArrayInputStream(data.getBytes()); OutputStream os = client.storeFileStream(fileName)) { byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read);//from w w w . j a v a 2 s.com } } showServerReply(client); // finalize the file transfer boolean done = client.completePendingCommand(); if (done) { LOGGER.debug("File uploaded successfully."); } else { LOGGER.error("Failed to upload file."); } }
From source file:com.claim.support.FtpUtil.java
public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {/*www . j a va 2 s . c o m*/ FtpProperties properties = new ResourcesProperties().loadFTPProperties(); ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); File secondLocalFile = new File(direcPath); String secondRemoteFile = "WorkshopDay2.docx"; inputStream = new FileInputStream(secondLocalFile); System.out.println("Start uploading second file"); OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftpClient.completePendingCommand(); if (completed) { System.out.println("The second file is uploaded successfully."); } } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:com.zurich.sds.sino.utils.UploadZurichFTP.java
public void controller(FTPClient ftpClient, String preaperUpDirPath, String remoteDirPath_dir) throws FileNotFoundException, IOException { //FTPClient ftpClient = new FTPClient(); try {// w w w .j av a 2 s . c om // APPROACH #2: uploads second file using an OutputStream File secondLocalFile = new File(preaperUpDirPath + this.LocalFile); //System.out.println("..........LocalFile..prepare up load loc:"+secondLocalFile); String secondRemoteFile = remoteDirPath_dir + "/" + this.LocalFile; InputStream inputStream = new FileInputStream(secondLocalFile); System.out.println("..........iUPLOADj the file from " + secondLocalFile + " to " + secondRemoteFile); logger.info("..........iUPLOADj the file from " + secondLocalFile + " to " + secondRemoteFile); OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile); //ftpClient.deleteFile(secondRemoteFile); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftpClient.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); logger.info("The file is uploaded successfully."); setCompleted(completed); } } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); logger.info("Error: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java
public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName, String originalFileName) { if (logger.isDebugEnabled()) { logger.debug("SampleUploadCluster.process called"); }/*from w w w .j a v a2 s. c o m*/ FTPClient ftp = new FTPClient(); OutputStream out = null; File file = new File(sourceRepositoryPath + "/" + maskingFileName); FileInputStream fin = null; BufferedInputStream bin = null; String storeFileName = null; String server = "?IP";//?? ? . ex) 210.25.3.21 try { ftp.connect(server); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); storeFileName = maskingFileName + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()); fin = new FileInputStream(file); bin = new BufferedInputStream(fin); ftp.login("testId", "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length())); if (logger.isDebugEnabled()) { logger.debug(server + " connect success !!! "); } ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/"); out = ftp.storeFileStream(storeFileName); FileCopyUtils.copy(fin, out); if (logger.isDebugEnabled()) { logger.debug(" cluster success !!! "); } } else { ftp.disconnect(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); if (bin != null) bin.close(); ftp.logout(); out = null; bin = null; } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:com.dinochiesa.edgecallouts.FtpPut.java
public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) { FtpCalloutResult info = new FtpCalloutResult(); try {/* w w w . j a va2 s. c o m*/ // The executes in the IO thread! String sourceVar = getSourceVar(messageContext); InputStream src = null; boolean wantBase64Decode = getWantBase64Decode(messageContext); if (sourceVar == null) { src = messageContext.getMessage().getContentAsStream(); // conditionally wrap a decoder around it if (wantBase64Decode) { src = new Base64InputStream(src); } } else { info.addMessage("Retrieving data from " + sourceVar); String sourceData = messageContext.getVariable(sourceVar); byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData) : sourceData.getBytes(StandardCharsets.UTF_8); src = new ByteArrayInputStream(b); } String remoteName = getRemoteFileName(messageContext); remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-"); String ftpServer = getFtpServer(messageContext); int ftpPort = getFtpPort(messageContext); String user = getFtpUser(messageContext); String password = getFtpPassword(messageContext); info.addMessage("connecting to server " + ftpServer); FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new FtpCommandListener(info)); ftp.connect(ftpServer, ftpPort); ftp.enterLocalPassiveMode(); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); info.setStatus("FAIL"); info.addMessage("The FTP server refused the connection."); messageContext.setVariable(varName("result"), info.toJsonString()); return ExecutionResult.ABORT; } if (!ftp.login(user, password)) { ftp.disconnect(); info.setStatus("FAIL"); info.addMessage("Login failure"); messageContext.setVariable(varName("result"), info.toJsonString()); return ExecutionResult.ABORT; } info.addMessage("logged in as " + user); String initialDirectory = getInitialDirectory(messageContext); if ((initialDirectory != null) && (!initialDirectory.equals(""))) { ftp.changeWorkingDirectory(initialDirectory); } ftp.setFileType(FTP.BINARY_FILE_TYPE); OutputStream os = ftp.storeFileStream(remoteName); if (os == null) { // cannot open output stream info.addMessage("cannot open output stream to " + remoteName); info.setStatus("FAIL"); } else { byte[] buf = new byte[2048]; int n; while ((n = src.read(buf)) > 0) { os.write(buf, 0, n); } os.close(); src.close(); boolean completed = ftp.completePendingCommand(); info.addMessage("transfer completed: " + completed); info.setStatus("OK"); } ftp.disconnect(); info.addMessage("All done."); messageContext.setVariable(varName("result"), info.toJsonString()); } catch (java.lang.Exception exc1) { if (getDebug()) { System.out.println(ExceptionUtils.getStackTrace(exc1)); } String error = exc1.toString(); messageContext.setVariable(varName("exception"), error); info.setStatus("FAIL"); info.addMessage(error); messageContext.setVariable(varName("result"), info.toJsonString()); int ch = error.lastIndexOf(':'); if (ch >= 0) { messageContext.setVariable(varName("error"), error.substring(ch + 2).trim()); } else { messageContext.setVariable(varName("error"), error); } messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1)); return ExecutionResult.ABORT; } return ExecutionResult.SUCCESS; }
From source file:com.cladonia.xngreditor.URLUtilities.java
public static void save(URL url, InputStream input, String encoding) throws IOException { // System.out.println( "URLUtilities.save( "+url+", "+encoding+")"); String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("ftp")) { FTPClient client = null; String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host);/*w w w . jav a2 s . c o m*/ // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Disconnecting..."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Writing output ..."); OutputStream output = client.storeFileStream(url.getFile()); // if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) { // output.close(); // client.disconnect(); // throw new IOException( "Could not transfer file \""+url.getFile()+"\"."); // } InputStreamReader reader = new InputStreamReader(input, encoding); OutputStreamWriter writer = new OutputStreamWriter(output, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); output.close(); // Must call completePendingCommand() to finish command. if (!client.completePendingCommand()) { client.disconnect(); throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } else { client.disconnect(); } } else if (protocol.equals("http") || protocol.equals("https")) { WebdavResource webdav = createWebdavResource(toString(url), username, password); if (webdav != null) { webdav.putMethod(url.getPath(), input); webdav.close(); } else { throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } } else if (protocol.equals("file")) { FileOutputStream stream = new FileOutputStream(toFile(url)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding)); InputStreamReader reader = new InputStreamReader(input, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); } else { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } }