Загрузка файлов на ftp java

Java FTP file upload tutorial and example

To write Java code that uploads a file from local computer to a remote FTP server, the Apache Commons Net API is a preferred choice of developers. It has simple and comprehensive API that makes coding with upload files to FTP server with ease.

Table of Content:

1. Apache Commons Net API for uploading files by FTP protocol

The FTPClient class provides six storeXXX() methods for transferring a local file to a remote server via FTP protocol:

    • boolean storeFile(String remote, InputStream local)
    • OutputStreamstoreFileStream(String remote)
    • boolean storeUniqueFile(InputStream local)
    • boolean storeUniqueFile(String remote, InputStream local)
    • OutputStreamstoreUniqueFileStream()
    • OutputStreamstoreUniqueFileStream(String remote)
      • Store files by providing anInputStream of the local file (those methods which have an InputStream as a parameter). This type of methods can be used when we don’t care how the bytes are transferred from the local file to the remote one, just let the system done the ins and outs.
      • Store files by writing to anOutputStream of the connection (those methods which return an OutputStream ). This type of methods is needed when we want to control how the bytes are transferred, by writing our own code for reading bytes from the local file and write these bytes to the remote file through the OutputStream object. This can be useful if we want to show progress of the upload, by calculating how many bytes are transferred over total bytes needed.

      The two ways above can be used in combination with:

        • Name the remote file explicitly (those methods which accept a String parameter called remote ).
        • Let the server names the remote file with a unique name (those methods which do not have a String parameter).
          • boolean storeFile(String remote, InputStream local)
          • OutputStreamstoreFileStream(String remote)
            • boolean setFileType(int fileType ) : determines which file type, either FTP.ASCII_FILE_TYPE or FTP.BINARY_FILE_TYPE , is used for file transfer. The default type is ASCII (plain text file), but it should be set to binary type in order to work with any files. This method must be called before a file transfer starts.
            • boolean completePendingCommand() : This method should be called after file transfer finishes, to complete the transaction entirely. It would return true if successfully completed, or false otherwise. We should check return value of this method to ensure the upload is actually successful. However, this method may not be necessary for some of storeXXX() methods.

            So it is recommended to switch to local passive mode before transferring data, by invoking the method enterLocalPassiveMode() of the FTPClient class.

            2. The proper steps to upload a file to FTP server

            To properly write code to upload files to a FTP server using Apache Commons Net API, the following steps should be followed:

              • Connect and login to the server.
              • Enter local passive mode for data connection.
              • Set file type to be transferred to binary.
              • Create an InputStream for the local file.
              • Construct path of the remote file on the server. The path can be absolute or relative to the current working directory.
              • Call one of the storeXXX() methods to begin file transfer. There are two scenarios:
                • Using an InputStream -based approach: this is the simplest way, since we let the system does the ins and outs. There is no additional code, just passing the InputStream object into the appropriate method, such as storeFile (String remote, InputStream local) method.
                • Using an OutputStream -based approach: this is more complex way, but more control. Typically we have to write some code that reads bytes from the InputStream of the local file and writes those bytes into the OutputStream which is returned by the storeXXX() method, such as storeFileStream (String remote) method.

                3. Java FTP File Upload Sample program code

                The following sample program demonstrates uploading local files to a FTP server using these two methods:

                  • boolean storeFile(String remote, InputStream local)
                  • OutputStreamstoreFileStream(String remote)
                  import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; /** * A program that demonstrates how to upload files from local computer * to a remote FTP server using Apache Commons Net API. * @author www.codejava.net */ public class FTPUploadFileDemo < public static void main(String[] args) < String server = "www.myserver.com"; int port = 21; String user = "user"; String pass = "pass"; FTPClient ftpClient = new FTPClient(); try < ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // APPROACH #1: uploads first file using an InputStream File firstLocalFile = new File("D:/Test/Projects.zip"); String firstRemoteFile = "Projects.zip"; InputStream inputStream = new FileInputStream(firstLocalFile); System.out.println("Start uploading first file"); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) < System.out.println("The first file is uploaded successfully."); >// APPROACH #2: uploads second file using an OutputStream File secondLocalFile = new File("E:/Test/Report.doc"); String secondRemoteFile = "test/Report.doc"; 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(); >> > >

                  To work with Apache Commons Net API, the commons-net-VERSION.jar file must be added to the classpath. The jar file can be picked up from within a zip distribution which can be downloaded from http://commons.apache.org/net/download_net.cgi.

                  Other Java File Upload Tutorials:

                  Other Java FTP Tutorials:

                  About the Author:

                  Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

                  Источник

                  Реализация FTP-клиента на Java

                  Узнайте, как легко взаимодействовать с внешним FTP-сервером на Java.

                  1. Обзор

                  В этом уроке мы рассмотрим, как использовать Apache Commons Net библиотека для взаимодействия с внешним FTP-сервером.

                  2. Настройка

                  При использовании библиотек, которые используются для взаимодействия с внешними системами, часто рекомендуется написать несколько дополнительных интеграционных тестов, чтобы убедиться, что мы правильно используем библиотеку.

                  В настоящее время мы обычно используем Docker для запуска этих систем для наших интеграционных тестов. Однако, особенно при использовании в пассивном режиме, FTP-сервер не является самым простым приложением для прозрачного запуска внутри контейнера, если мы хотим использовать динамические сопоставления портов (что часто необходимо для выполнения тестов на общем сервере CI).

                  Вот почему мы будем использовать MockFtpServer вместо этого, поддельный/тупиковый FTP-сервер, написанный на Java, который предоставляет обширный API для удобного использования в тестах JUnit:

                   commons-net commons-net 3.6  org.mockftpserver MockFtpServer 2.7.1 test 

                  Рекомендуется всегда использовать последнюю версию. Их можно найти здесь и там .

                  3. Поддержка FTP в JDK

                  Удивительно, но в некоторых вариантах JDK уже есть базовая поддержка FTP в виде Удивительно, но в некоторых вариантах JDK уже есть базовая поддержка FTP в виде .

                  Однако мы не должны использовать этот класс напрямую, и вместо этого можно использовать JDK java.net. Класс URL как абстракция.

                  Эта поддержка FTP очень проста, но использует удобные API-интерфейсы java.nio.file.Файлы, этого может быть достаточно для простых случаев использования:

                  @Test public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException < String ftpUrl = String.format( "ftp://user:[email protected]:%d/foobar.txt", fakeFtpServer.getServerControlPort()); URLConnection urlConnection = new URL(ftpUrl).openConnection(); InputStream inputStream = urlConnection.getInputStream(); Files.copy(inputStream, new File("downloaded_buz.txt").toPath()); inputStream.close(); assertThat(new File("downloaded_buz.txt")).exists(); new File("downloaded_buz.txt").delete(); // cleanup >

                  Поскольку в этой базовой поддержке FTP уже отсутствуют основные функции, такие как списки файлов, мы будем использовать поддержку FTP в библиотеке Apache Net Commons в следующих примерах.

                  4. Подключение

                  Сначала нам нужно подключиться к FTP-серверу. Давайте начнем с создания класса FTPClient.

                  Он будет служить в качестве API абстракции для реального FTP-клиента Apache Commons Net:

                  class FtpClient < private String server; private int port; private String user; private String password; private FTPClient ftp; // constructor void open() throws IOException < ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(server, port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) < ftp.disconnect(); throw new IOException("Exception in connecting to FTP Server"); >ftp.login(user, password); > void close() throws IOException < ftp.disconnect(); >>

                  Нам нужен адрес сервера и порт, а также имя пользователя и пароль. После подключения необходимо проверить код ответа, чтобы убедиться, что соединение прошло успешно. Мы также добавляем PrintCommandListener , чтобы распечатать ответы, которые мы обычно видим при подключении к FTP-серверу с помощью инструментов командной строки в stdout.

                  Поскольку наши интеграционные тесты будут иметь некоторый шаблонный код, такой как запуск/остановка MockFtpServer и подключение/отключение нашего клиента, мы можем сделать это в методах @Before и @After :

                  public class FtpClientIntegrationTest < private FakeFtpServer fakeFtpServer; private FtpClient ftpClient; @Before public void setup() throws IOException < fakeFtpServer = new FakeFtpServer(); fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); FileSystem fileSystem = new UnixFakeFileSystem(); fileSystem.add(new DirectoryEntry("/data")); fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); fakeFtpServer.setFileSystem(fileSystem); fakeFtpServer.setServerControlPort(0); fakeFtpServer.start(); ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password"); ftpClient.open(); >@After public void teardown() throws IOException < ftpClient.close(); fakeFtpServer.stop(); >>

                  Установив порт управления фиктивным сервером в значение 0, мы запускаем фиктивный сервер и свободный случайный порт.

                  Вот почему мы должны получить фактический порт при создании Ftp-клиента после запуска сервера, используя fakeFtpServer.getServerControlPort() .

                  5. Список файлов

                  Первым фактическим вариантом использования будет список файлов.

                  Давайте сначала начнем с теста в стиле TDD:

                  @Test public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException < Collectionfiles = ftpClient.listFiles(""); assertThat(files).contains("foobar.txt"); >

                  Сама реализация столь же проста. Чтобы сделать возвращаемую структуру данных немного проще для этого примера, мы преобразуем возвращаемый FTPFile массив преобразуется в список Строк с помощью Java 8 Потоков:

                  Collection listFiles(String path) throws IOException

                  6. Загрузка

                  Для загрузки файла с FTP-сервера мы определяем API.

                  Здесь мы определяем исходный файл и место назначения в локальной файловой системе:

                  @Test public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException < ftpClient.downloadFile("/buz.txt", "downloaded_buz.txt"); assertThat(new File("downloaded_buz.txt")).exists(); new File("downloaded_buz.txt").delete(); // cleanup >

                  FTP-клиент Apache Net Commons содержит удобный API, который будет напрямую записывать данные в определенный выходной поток. Это означает, что мы можем использовать это напрямую:

                  void downloadFile(String source, String destination) throws IOException

                  7. Загрузка

                  MockFtpServer предоставляет некоторые полезные методы для доступа к содержимому своей файловой системы. Мы можем использовать эту функцию для написания простого интеграционного теста для функции загрузки:

                  @Test public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException < File file = new File(getClass().getClassLoader().getResource("baz.txt").toURI()); ftpClient.putFileToPath(file, "/buz.txt"); assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue(); >

                  Загрузка файла работает с точки зрения API очень похоже на его загрузку, но вместо использования OutputStream нам нужно предоставить InputStream вместо этого:

                  void putFileToPath(File file, String path) throws IOException

                  8. Заключение

                  Мы видели, что использование Java вместе с Apache Net Commons позволяет нам легко взаимодействовать с внешним FTP-сервером как для чтения, так и для записи.

                  Как обычно, полный код этой статьи доступен в нашем репозитории GitHub .

                  Читайте ещё по теме:

                  Источник

                  Загрузка файлов на ftp java

                  Free tutorials with examples : learn IT & improve your IT skills.

                  Enterprise / Solution Architect

                  This article will explain you how to upload a file using FTP in Java. This tutorial will show you an example as well.

                  Upload a file using FTP in Java (with example)

                  Sometimes you need to create a Java FTP client to upload a file to a FTP server.

                  package ftp.upload.java; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; public class FtpUploadJavaExample < public static void main(String[] args) < FTPClient ftpClient = new FTPClient(); try < ftpClient.connect("192.168.6.130", 21); ftpClient.login("oracle", "1"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); File LocalFile = new File("C:/JAVA/EJBClient.jar"); String remoteFile = "/u01/dir1/EJBClient.jar"; InputStream inputStream = new FileInputStream(LocalFile); System.out.println("Start uploading first file"); boolean done = ftpClient.storeFile(remoteFile, inputStream); inputStream.close(); if (done) < System.out.println("The first file is uploaded using FTP 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(); >> > >

                  For this example you have to download and add to the project the commons-net-3.6.jar file:

                  Upload file using FTP Client in Java : commons net library

                  If the upload is done successfully , you will see into the console, the following:

                  Upload file using FTP Client in Java : successfully

                  If the FTP server is stopped, you can see the following error:

                  Upload file using FTP Client in Java : error

                  LEARN-IT-WITH-EXAMPLES.com

                  Источник

                  Читайте также:  Визуализация деревьев решений python
Оцените статью