Java uploads files to FTP (FTP service in CentOS)

Source: Internet
Author: User
Tags create directory ftp login

System: CENTOS7

Pom.xml Dependency

 <Dependency>      <groupId>Commons-net</groupId>      <Artifactid>Commons-net</Artifactid>      <version>3.3</version> </Dependency>

Code:

ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportOrg.apache.commons.net.ftp.FTP;Importorg.apache.commons.net.ftp.FTPClient;ImportOrg.apache.commons.net.ftp.FTPFile;Importorg.apache.commons.net.ftp.FTPReply;/*** FTP upload Download Tool class * <p>Title:FtpUtil</p> * <p>description: </p> * <p>company:www.itcast.c Om</p> *@authorinto Yunlong * @date July 29, 2015 afternoon 8:11:51 *@version1.0*/ Public classFtputil {/*** Description: Uploading files to FTP server *@paramHost FTP server hostname *@paramPort FTP Server ports *@paramUsername FTP login Account *@paramPassword FTP login password *@parambasepath FTP Server base directory *@paramFilePath FTP Server file storage path. For example, the date of storage:/2015/01/01. The path to the file is Basepath+filepath *@paramfilename uploaded to the FTP server *@paramInput Stream *@returnSuccess returns True, otherwise false*/       Public Static BooleanUploadFile (String host,intport, string Username, string password, string basepath, String filePath, string filename, InputStream in Put) {Booleanresult =false; FtpClient FTP=Newftpclient (); Try {            intreply; Ftp.connect (host, port);//connecting to an FTP server//If you use the default port, you can connect directly to the FTP server using Ftp.connect (host)Ftp.login (username, password);//LoginReply =Ftp.getreplycode (); if(!ftpreply.ispositivecompletion (Reply))                {Ftp.disconnect (); return false; }            //switch to upload directory            if(!ftp.changeworkingdirectory (basepath+FilePath)) {                //Create directory If directory does not existstring[] dirs = Filepath.split ("/"); //BasePath should exist first .                if(!ftp.changeworkingdirectory (BasePath)) {                    return false; }                 for(String dir:dirs) {if(NULL= = Dir | | "". Equals (dir)Continue; if(!ftp.changeworkingdirectory (dir)) {                        //If you cannot create a folder                        if(!ftp.makedirectory (dir)) {                            return false; }                        Else //switch to current directory after folder creation{ftp.changeworkingdirectory (dir); }                    }                }            }            //set the type of upload file to binary typeFtp.setfiletype (Ftp.binary_file_type); //Uploading Files            if(!ftp.storefile (filename, input)) {                returnresult;            } input.close ();            Ftp.logout (); Result=true; } Catch(IOException e) {e.printstacktrace (); } finally {            if(ftp.isconnected ()) {Try{ftp.disconnect (); } Catch(IOException IoE) {}}} returnresult; }        /*** Description: Download files from FTP server *@paramHost FTP server hostname *@paramPort FTP Server ports *@paramUsername FTP login Account *@paramPassword FTP login password *@paramRemotePath The relative path on the FTP server *@paramfilename to download *@paramLocalPath saved to local path after download *@return      */       Public Static BooleanDownloadFile (String host,intport, string Username, string password, string remotepath, String fileName, String localPath) {        Booleanresult =false; FtpClient FTP=Newftpclient (); Try {            intreply;            Ftp.connect (host, Port); //If you use the default port, you can connect directly to the FTP server using Ftp.connect (host)Ftp.login (username, password);//LoginReply =Ftp.getreplycode (); if(!ftpreply.ispositivecompletion (Reply))                {Ftp.disconnect (); returnresult; } ftp.changeworkingdirectory (RemotePath);//Transfer to FTP server directoryftpfile[] fs =Ftp.listfiles ();  for(Ftpfile ff:fs) {if(Ff.getname (). Equals (FileName)) {File LocalFile=NewFile (LocalPath + "/" +ff.getname ()); OutputStream is=NewFileOutputStream (LocalFile);                    Ftp.retrievefile (Ff.getname (), is);                Is.close ();            }} ftp.logout (); Result=true; } Catch(IOException e) {e.printstacktrace (); } finally {            if(ftp.isconnected ()) {Try{ftp.disconnect (); } Catch(IOException IoE) {}}} returnresult; }         Public Static voidMain (string[] args) {Try{FileInputStream in=NewFileInputStream (NewFile ("E:\\picture\\wade.jpg")); BooleanFlag = UploadFile ("192.168.1.105", +, "Ftpuser", "Ftpuser", "Pub/images", "/2015/1/21", "gaigeming.jpg", in);          SYSTEM.OUT.PRINTLN (flag); } Catch(FileNotFoundException e) {e.printstacktrace (); }      }}

Attention:

1.changeWorkingDirectory () returns false to switch working directory failure.

Changeworkingdirectory (), the directory on which the switch is based is relative to the current directory, not relative to the root directory. You are now in the Dri1 directory, then Changeworkingdirectory ("Dir1_1") switches to "dir1/dir1_1".

2.makeDirectory (path) returns FALSE. 

Cause 1:

Folder permissions, the folder I uploaded images is created with the root user, permissions: drwxr-xr-x. 4 root root 4096 02:28 images, we do not have write permissions when we use FTP users, so we cannot create a folder.

Workaround:

Modify folder permissions. (Note that FTP users should have the permissions of the parent folder and subfolders, my Upload folder is "Pub/images", the FTP user should have write permission to the pub, the images also have write permission).

Search the internet for a bit, there are reasons for 2.

Cause 2:

Since I am using a regular account login, I set up chroot_local_user=yes in the first place and locked the user in the host directory, which always prevents the creation of the directory. However, you can upload files, however, the uploaded files can only be stored in the host directory, that is,/home/test/xxx.txt.

Workaround:

Chroot_local_user=no in the vsftpd.conf file will be restarted vsftpd.

After I will chroot_local_user=ye and restart the service, Makedirectory (path) unexpectedly returns True,???

Java uploads files to FTP (FTP service in CentOS)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.