Java upload, download, delete ftp files

Source: Internet
Author: User
Tags ftp commands

Altogether three classes, a tool class Ftputil., an entity class Kmconfig. A test class

Download Address: http://download.csdn.net/detail/myfmyfmyfmyf/6697107

Ftputil class---------------

Package Ftpdemo;
Import Java.io.DataOutputStream;
Import Java.io.InputStream;

Import Java.io.OutputStream;
Import Sun.net.TelnetInputStream;
Import Sun.net.TelnetOutputStream;



Import sun.net.ftp.FtpClient; public class Ftputil {//upload file to ftp common method public static void Uploadfileftp (Kmconfig kmconfig,inputstream is, String Filenam
			E) {try {String ftphost = Kmconfig.getftphost ();
			int port = Kmconfig.getftpport ();
			String userName = Kmconfig.getftpuser ();
			String PassWord = Kmconfig.getftppassword ();
			

			String path = Kmconfig.getftppath ();
			FtpClient ftpclient = new FtpClient (ftphost, port);//Ftphost is the IP address of the FTP server, port is the FTP server's landing ports, the Ftphost is string type, port is int type.
			Ftpclient.login (UserName, PassWord);//UserName, PassWord for FTP server login username and password ftpclient.binary ();

			FTPCLIENT.CD (path);/path saves the upload file path for the FTP server. Telnetoutputstream telnetout = ftpclient.put (filename);/filename for the uploaded filename dataoutputstream dataout = new Dataoutputstre
			AM (telnetout); byte buffer[] = new BYTe[1024 * 1024];
			int count = 0;
			while ((count = is.read (buffer))!=-1) {dataout.write (buffer, 0, count);
			} telnetout.close ();
			Dataout.close ();
		Ftpclient.closeserver (); catch (Exception e) {System.out.println ("failed to upload file.")
		Please check the system FTP settings and verify that the FTP service is started "); //delete files to ftp common method public static void Deletefileftp (Kmconfig kmconfig,string fileName) {try {String ftphost = k
			Mconfig.getftphost ();
			int port = Kmconfig.getftpport ();
			String userName = Kmconfig.getftpuser ();
			String PassWord = Kmconfig.getftppassword ();

			String path = Kmconfig.getftppath ();
			FtpClient ftpclient = new FtpClient (ftphost, port);//Ftphost is the IP address of the FTP server, port is the FTP server's landing ports, the Ftphost is string type, port is int type.
			Ftpclient.login (UserName, PassWord);//UserName, PassWord for FTP server login username and password ftpclient.binary ();
			FTPCLIENT.CD (path);/path saves the upload file path for the FTP server.
			try {ftpclient.sendserver ("dele" + fileName + "\ r \ n"); The catch (Exception e) {System.out.println ("delete file failed.) Please check the system FTP settings and verify that the FTP service is openMovement ");
		} ftpclient.closeserver (); The catch (Exception e) {System.out.println ("delete file failed.)
		"); }///download FTP files public static void Downloadfileftp (Kmconfig kmconfig,string fileName, String clientfilename, Outputstre
			Am OutputStream) {try {String ftphost = Kmconfig.getftphost ();
			int port = Kmconfig.getftpport ();
			String userName = Kmconfig.getftpuser ();
			String PassWord = Kmconfig.getftppassword ();

			String path = Kmconfig.getftppath ();
			FtpClient ftpclient = new FtpClient (ftphost, port);//Ftphost is the IP address of the FTP server, port is the FTP server's landing ports, the Ftphost is string type, port is int type.
			Ftpclient.login (UserName, PassWord);//UserName, PassWord for FTP server login username and password ftpclient.binary ();
			FTPCLIENT.CD (path);/path saves the upload file path for the FTP server.
				try {telnetinputstream in = Ftpclient.get (FileName);
				byte[] bytes = new byte[1024];
				int cnt=0;
				while ((Cnt=in.read (bytes,0,bytes.length))!=-1) {outputstream.write (bytes, 0, CNT);
				} outputstream.close ();
			In.close (); catch (ExCeption e) {ftpclient.closeserver ();
			E.printstacktrace ();
		} ftpclient.closeserver (); catch (Exception e) {System.out.println ("failed to download the file.")
		Please check the system FTP settings and verify that the FTP service is started ");  
              
           
			}///On FTP server folder public boolean createdir (String path,ftpclient ftpclient) throws exception{  
            Go to the home folder under FTPCLIENT.CD ("/home"); Create remote folder//remote command includes//user PORT RETR ALLO DELE SITE xmkd cdup feat<    br>//Pass PASV STOR REST CWD STAT RMD xcup opts<br>//ACCT TYPE AppE rnfr xcwd help XRMD Stou auth<br>//REIN stru smnt-Rnto LI    ST NOOP PWD SIZE pbsz<br>//QUIT MODE syst abor NLST MKD xpwd-MDTM      Prot<br>//Execute commands on the server, and if you use Sendserver to execute remote commands (you cannot execute local FTP commands), all FTP commands are added with/r/n<br>//              Ftpclient.sendserver ("xmkd/test/bb/r/n");                    Execute FTP command on the server <br>//Ftpclient.readserverresponse must be called after Sendserver <br>//                    NameList ("/test") gets the list of files in the directory <br>//XMKD set up the directory, and when the directory exists, recreate the directory times wrong <br>//   
            XRMD Delete directory <br>//DELE Delete file <br>//through remote command to wear a Files folder  
            Ftpclient.sendserver ("MKD" + path + "\ r \ n");  
            This method must be called in the middle of these two methods otherwise the command regardless of using ftpclient.binary ();  
              
            Ftpclient.readserverresponse ();  
        return false;  /** * Check if folder exists * @param dir * @param ftpclient * @return/public boolean isdirexist (String dir, 
	  	FtpClient ftpclient) {try {ftpclient.cd (dir); 
	  	catch (Exception e) {return false; 
	return true;
 } 

}


Kmconfig class---------------

Package Ftpdemo;

public class Kmconfig {
	//host IP
	private String ftphost = "";
	Port number
	private int ftpport;
	FTP user name
	private String ftpuser = "";
	FTP password
	private String FTPPassword = "";
	Directory
	private String Ftppath = "" In FTP;
	Public String Getftphost () {return
		ftphost;
	}
	public void Setftphost (String ftphost) {
		ftphost = ftphost;
	}
	public int Getftpport () {return
		ftpport;
	}
	public void Setftpport (int ftpport) {
		ftpport = FtpPort;
	}
	Public String Getftpuser () {return
		ftpuser;
	}
	public void Setftpuser (String ftpuser) {
		ftpuser = ftpuser;
	}
	Public String Getftppassword () {return
		FTPPassword;
	}
	public void Setftppassword (String ftppassword) {
		FTPPassword = FTPPassword;
	}
	Public String Getftppath () {return
		ftppath;
	}
	public void Setftppath (String ftppath) {
		ftppath = Ftppath;
	}
	
	
	
}


Test class---------------

Package Ftpdemo;

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.InputStream;

public class Test {public
	static void Main (string[] args) {
		//Set ftp
		kmconfig km = new Kmconfig ();
		Km.setftphost ("172.20.32.48");
		Km.setftpport ();
		Km.setftpuser ("test");
		Km.setftppassword ("111111");
		Km.setftppath ("KM");
		
		Upload to FTP
		ftputil util=new ftputil ();
		File File = new file ("f:/article 2.jpg");
		InputStream in;
		try {in
			= new FileInputStream (file);
			Util.uploadfileftp (km, in, "changed name. jpg");
		} catch (FileNotFoundException e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		}
		
		
		Page access: ftp://account: Password @ip Address: Port number/folder directory///  ftp://test:111111@222.22.22.11:21/image/
	}


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.