Java Language Подключение и вход в FTP-сервер. Java Language Подключение и вход в FTP-сервер Скачать файл с ftp сервера java

Java Language Подключение и вход в FTP-сервер. Java Language Подключение и вход в FTP-сервер Скачать файл с ftp сервера java

03.11.2019
35 Comments

Java FTP Client is used to upload files to FTP server. Recently I was working in a web project where I had to upload a lot of images to the FTP server. Few days back, I wrote a program to resize image in java . My actual program was to resize all the images in a directory and then upload to FTP server using Apache Commons Net API.

Java FTP Client Example

Here I am providing a Java FTP client program to upload files to FTP server using Apache Commons Net API.

package com.journaldev.inheritance; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import org.apache.commons.net.PrintCommandListener; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPUploader { FTPClient ftp = null; public FTPUploader(String host, String user, String pwd) throws Exception{ ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); int reply; ftp.connect(host); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("Exception in connecting to FTP Server"); } ftp.login(user, pwd); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); } public void uploadFile(String localFileFullName, String fileName, String hostDir) throws Exception { try(InputStream input = new FileInputStream(new File(localFileFullName))){ this.ftp.storeFile(hostDir + fileName, input); } } public void disconnect(){ if (this.ftp.isConnected()) { try { this.ftp.logout(); this.ftp.disconnect(); } catch (IOException f) { // do nothing as file is already saved to server } } } public static void main(String args) throws Exception { System.out.println("Start"); FTPUploader ftpUploader = new FTPUploader("ftp.journaldev.com", "ftpUser", "ftpPassword"); //FTP server path is relative. So if FTP account HOME directory is "/home/pankaj/public_html/" and you need to upload // files to "/home/pankaj/public_html/wp-content/uploads/image2/", you should pass directory parameter as "/wp-content/uploads/image2/" ftpUploader.uploadFile("D:\\Pankaj\\images\\MyImage.png", "image.png", "/wp-content/uploads/image2/"); ftpUploader.disconnect(); System.out.println("Done"); } }

You can use the above program to connect to an FTP server and then upload files to the server. Make sure you provide FTP Host, user, and password details correctly in the program. You can get these details when you create an FTP user.

This technique is based on RFC1738 specification which defines URL format for FTP access. This application downloads a file from the server and list out the size of downloading file and the time consumed in the downloading.

Objective

In this tutorial, we will learn:

  • What is FTP?
  • Advantages and Disadvantages

What is FTP?

FTP (File Transfer Protocol) is the simplest and most secure way to exchange files over the Internet. FTP is a fast and reliable method for transferring files between two remote computers, using the Internet. A basic FTP connection consists of a remote computer (the client) calling an FTP server. FTP connections transmit information in two ways: the client may upload content from the server or download content to the server.

In order to make a connection, simply direct the “client” to connect to a specific FTP server.

In order to transfer a file (upload or download) through FTP:

  • Log in to a remote computer that has been configured as an FTP server.
  • Enter a username and password to gain access to the remote system.
  • Select the particular directory on the remote system, which contains the file you wish to download or upload.
  • Transfer the file to or from the system.

How do we java code to download a file from your FTP server?

In this article we will learn how to use the class i.e. java.net.URLConnection to download a remote file from a FTP server, without using a third party servers like Apache, Tomcat Servers. The technique is based on RFC1738 specification which defines URL format for FTP access as follows: ftp://username:password@hostname:port/path

This URL scheme is called FTP URL, where:

  • username: is the user name of a FTP account on the FTP server to connect to.
  • password: is the password corresponds to the user name.
  • hostname: is the host name or IP address of the FTP server.
  • port: Is the port number on which the server is listening.
  • path: Path of the remote file in the following form:

//...//;type=

  • //.../ : are path elements which form a particular directory structure (the word means directory).
  • : file/directory name.
  • :type= : this is the optional part. This part specifies the transfer mode where typecode can be one of the characters: a (ASCII - text mode), i (IMAGE - binary mode), d (Directory listing). If this part is omitted or regretted, the client has to guess the appropriate mode.

For example, if you want to download a zip file Project.zip under path /myproject/2013 on the host www.myclientserver.com using user oracle and password secret, construct the following URL: ftp://oracle:[email protected]/myproject/2013/Project.zip;type=i

Paste that URL into browser’s address bar and it will handle the file download.

In Java, we use the class name: URLConnection to open a connection on a FTP URL, and after that obtain a input stream of the opened connection to read bytes data. Use a file output stream to save the bytes into a file.

For example:

  • String ftpUrl = "ftp://oracle:[email protected]/myproject/2013/Project.zip;type=i";
  • String saveFile = "Project.zip";
  • URL url = new URL(ftpUrl);
  • URLConnection conn = url.openConnection();
  • InputStream inputStream = conn.getInputStream();
  • FileOutputStream outputStream = new FileOutputStream(saveFile); // reads from inputStream and write to outputStream

The below program describes how to use class URLConnection to download a file on a FTP server using FTP URL technique:

Moreover, this technique has its own advantages and disadvantages which are given below:

Listing 1 : Download.java

import java.io.FileOutputStream ; import java.io.IOException ; import java.io.InputStream ; import java.net.URL ; import java.net.URLConnection ; import java.io.File ; class Download{ private static final int BUFFER_SIZE = 4096 ; public void download(){ //this is a function long startTime = System.currentTimeMillis() ; String ftpUrl = ftp://**username**:**password**@filePath ; String file= "filename" ; // name of the file which has to be download String host = host_name ; //ftp server String user = "username" ; //user name of the ftp server String pass = "**password" ; // password of the ftp server String savePath = "c:\\" ; ftpUrl = String.format(ftpUrl, user, pass, host) ; System.out.println("Connecting to FTP server") ; try{ URL url = new URL(ftpUrl) ; URLConnection conn = url.openConnection() ; InputStream inputStream = conn.getInputStream() ; long filesize = conn.getContentLength() ; System.out.println("Size of the file to download in kb is:-" + filesize/1024) ; FileOutputStream outputStream = new FileOutputStream(savePath) ; byte buffer = new byte ; int bytesRead = -1 ; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead) ; } long endTime = System.currentTimeMillis() ; System.out.println("File downloaded") ; System.out.println("Download time in sec. is:-" + (endTime-startTime)/1000) ; outputStream.close() ; inputStream.close() ; } catch (IOException ex){ ex.printStackTrace() ; } } }

Listing 1 defines a java file “Download.java” that defines a mechanism to get connected with the ftp server using given url with the valid username and password. Once the connected is established with the given ftp url, the connection will be authenticated using the submitted username and password given into the ftp url. A java.net java API is used to establish to cover networking part of the application.

This class defines class variable:

  • BUFFER_SIZE: An integer type static variable that defines a buffer size of the stream to be kept downloading file content at a time.

download() : A method that invoke downloading connection and download a file from the server. It also defines a set of variables:

  • startTime : A long type variable that is initialized by current system time, this variable is used to list out the time consumed in the downloading.
  • ftpUrl : A string type variable to hold the url information that will be used to connect with the ftp host.
  • file : A string type variable that name the downloading file.
  • host : A string type variable that list the name of host that is to be connected.
  • user : A string type variable to hold username information.
  • password : A string type variable to hold password information.
  • savePath : A string type variable that holds the file location to save downloading file.
  • outputStream : A FileOutputStream type variable that output the downloading file to be saved in the given system location using “savePath” variable.
  • url : A URL class type variable that create request to hit on the given host using ftpUrl.
  • buffer : A byte array of size BUFFER_SIZE.
  • bytesRead : An integer type variable to hold information of receiving bytes from the server.
  • endTime : An integer type variable to current system time, when a file downloading ends.

Once the file has been downloaded, the downloading consumed time will be listed with the downloaded file size. The file will be read byte by byte using listed logic below:

while((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead) ; }

Once the file has been donwlaoded, it is our responsibility to close the opened FileOutputStream. To close the stream, we use close() method defined into FileOutputStream class.

An inputstream is used to get the data from the ftp server, it will accepts data in bytes stream using connection class method. To get byte stream, getInputStream() method is used. To get the downloading file getContentLength() method of connection is used. As we opened input stream, it is our responsibility to close this stream. To close input stream, close() method of InputStream class is used.

Once the file has been downloaded, the consumed tile is calculated using by subtracting startTime from endTime and divide it by 1000 as (endTime - startTime)/1000).

Listing 2 : FtpUrlDownload.java

public class FtpUrlDownload{ public static void main(String args){ Download d1 = new Download() ; d1.download() ; try{ Thread.sleep(500) ; } catch(Exception e) { System.out.println(c); } } }

Listing 2 defines a java file “FtpUrlDownload.java” that creates an instance of “Download” class and class a method named “download()” to download a file from given server url into download class. This class uses connection exception mechanism that may be occurred while trying to establish connection with the server, receiving data from ftp host and saving the downloaded file.

Advantages:

Simple to use, does not require third party FTP tool or application server.

Disadvantages:

Less flexibility and less control, there is no way to check FTP server’s response code. If the download fails in the middle, we have to start over the download because it’s impossible to resume the upload.

Conclusion:

Using this article, we learn about FTP protocol and its use. Here we created file download application using java.net API using to download an application for the given url and user authentication information. In this application, we came to learn about the file downloading process. We learn, how we calculate the size of downloading file, the time consumed in file downloading and save the file to system.

Чтобы начать использовать FTP с Java, вам нужно будет создать новый FTPClient а затем подключиться и войти на сервер с помощью.connect(String server, int port) и.login(String username, String password) .

Import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; //Import all the required resource for this project. public class FTPConnectAndLogin { public static void main(String args) { // SET THESE TO MATCH YOUR FTP SERVER // String server = "www.server.com"; //Server can be either host name or IP address. int port = 21; String user = "Username"; String pass = "Password"; FTPClient ftp = new FTPClient; ftp.connect(server, port); ftp.login(user, pass); } }

Теперь у нас есть основы. Но что, если у нас есть ошибка подключения к серверу? Мы хотим знать, когда что-то пойдет не так, и получите сообщение об ошибке. Давайте добавим код, чтобы поймать ошибки при подключении.

Try { ftp.connect(server, port); showServerReply(ftp); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.printIn("Operation failed. Server reply code: " + replyCode) return; } ftp.login(user, pass); } catch { }

Давайте сломаем то, что мы только что сделали, шаг за шагом.

ShowServerReply(ftp);

Это относится к функции, которую мы будем делать на более позднем этапе.

Int replyCode = ftp.getReplyCode();

Это захватывает код ответа / ошибки с сервера и сохраняет его как целое.

If (!FTPReply.isPositiveCompletion(replyCode)) { System.out.printIn("Operation failed. Server reply code: " + replyCode) return; }

Это проверяет код ответа, чтобы узнать, была ли ошибка. Если произошла ошибка, она просто выведет «Операция не выполнена. Код ответа сервера:», за которой следует код ошибки. Мы также добавили блок try / catch, который мы добавим на следующем шаге. Затем давайте создадим функцию, которая проверяет ftp.login() наличие ошибок.

Boolean success = ftp.login(user, pass); showServerReply(ftp); if (!success) { System.out.println("Failed to log into the server"); return; } else { System.out.println("LOGGED IN SERVER"); }

Давайте также сломаем этот блок.

Boolean success = ftp.login(user, pass);

Это не просто попытка входа на FTP-сервер, но и сохранение результата в виде логического.

ShowServerReply(ftp);

Это проверит, посылал ли сервер нам какие-либо сообщения, но сначала нам нужно создать функцию на следующем шаге.

If (!success) { System.out.println("Failed to log into the server"); return; } else { System.out.println("LOGGED IN SERVER"); }

Этот оператор проверяет, успешно ли мы вошли в систему; если это так, он напечатает «LOGGED IN SERVER», иначе он напечатает «Не удалось войти в сервер». Это наш скрипт:

Import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPConnectAndLogin { public static void main(String args) { // SET THESE TO MATCH YOUR FTP SERVER // String server = "www.server.com"; int port = 21; String user = "username" String pass = "password" FTPClient ftp = new FTPClient try { ftp.connect(server, port) showServerReply(ftp); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Operation failed. Server reply code: " + replyCode); return; } boolean success = ftp.login(user, pass); showServerReply(ftp); if (!success) { System.out.println("Failed to log into the server"); return; } else { System.out.println("LOGGED IN SERVER"); } } catch { } } }

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

} catch (IOException ex) { System.out.println("Oops! Something went wrong."); ex.printStackTrace(); }

Завершенный блок блокировки теперь будет печатать «Ой, что-то пошло не так». и stacktrace, если есть ошибка. Теперь наш последний шаг - создать showServerReply() мы использовали некоторое время.

Private static void showServerReply(FTPClient ftp) { String replies = ftp.getReplyStrings(); if (replies != null && replies.length > 0) { for (String aReply: replies) { System.out.println("SERVER: " + aReply); } } }

Эта функция принимает FTPClient как переменную и называет ее «ftp». После этого он хранит любые серверные ответы с сервера в массиве строк. Затем он проверяет, сохранены ли какие-либо сообщения. Если он есть, он печатает каждый из них как «СЕРВЕР: [ответ]». Теперь, когда мы выполнили эту функцию, это завершенный скрипт:

Import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPConnectAndLogin { private static void showServerReply(FTPClient ftp) { String replies = ftp.getReplyStrings(); if (replies != null && replies.length > 0) { for (String aReply: replies) { System.out.println("SERVER: " + aReply); } } } public static void main(String args) { // SET THESE TO MATCH YOUR FTP SERVER // String server = "www.server.com"; int port = 21; String user = "username" String pass = "password" FTPClient ftp = new FTPClient try { ftp.connect(server, port) showServerReply(ftp); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Operation failed. Server reply code: " + replyCode); return; } boolean success = ftp.login(user, pass); showServerReply(ftp); if (!success) { System.out.println("Failed to log into the server"); return; } else { System.out.println("LOGGED IN SERVER"); } } catch (IOException ex) { System.out.println("Oops! Something went wrong."); ex.printStackTrace(); } } }

Сначала нам нужно создать новый FTPClient и попробовать подключиться к серверу и войти в него с помощью.connect(String server, int port) и.login(String username, String password) . Важно подключиться и войти в систему с помощью блока try / catch, если наш код не сможет подключиться к серверу. Нам также необходимо создать функцию, которая проверяет и отображает любые сообщения, которые мы можем получать с сервера, когда мы пытаемся подключиться и войти в систему. Мы будем называть эту функцию « showServerReply(FTPClient ftp) ».

Import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPConnectAndLogin { private static void showServerReply(FTPClient ftp) { if (replies != null && replies.length > 0) { for (String aReply: replies) { System.out.println("SERVER: " + aReply); } } } public static void main(String args) { // SET THESE TO MATCH YOUR FTP SERVER // String server = "www.server.com"; int port = 21; String user = "username" String pass = "password" FTPClient ftp = new FTPClient try { ftp.connect(server, port) showServerReply(ftp); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Operation failed. Server reply code: " + replyCode); return; } boolean success = ftp.login(user, pass); showServerReply(ftp); if (!success) { System.out.println("Failed to log into the server"); return; } else { System.out.println("LOGGED IN SERVER"); } } catch (IOException ex) { System.out.println("Oops! Something went wrong."); ex.printStackTrace(); } } }

После этого вы должны теперь подключить свой FTP-сервер к вам Java-скрипту.



© 2024 beasthackerz.ru - Браузеры. Аудио. Жесткий диск. Программы. Локальная сеть. Windows