Java to do a more complete FTP connection upload download file

Source: Internet
Author: User
Tags add date format ftp ftp connection connect net string
Compare | upload | Download this is my first time to write Java program to achieve the company's requirements of the FTP data synchronization, all the original code as follows, for your reference and put forward valuable advice! In addition, I have two functions have not been achieved, please master Pointing twos: 1, how to delete the FTP server has been downloaded files? 2, how to upload the file name? Upload in front of the file name plus "Temp_", upload after the need to change the file name back. 3, how to use the Openpassivedataconnection () method to change the FTP connection to active connection, because the FTP server configured from the UNIX system to download files, you need to actively connect.



/*
*******************************************************************************************************

Filename:ftp.java
Author:leetsing (Elove)
Create date:2004-08-30
Use:connect to FTP server,then upload and download file
Modify date:2004-09-05 Add to upload file
2004-09-13 Add to download file
Copy Right:magisky Media Technology co.,ltd.

*******************************************************************************************************
*/
Import cz.dhl.io.*;
Import cz.dhl.ftp.*;
Import sun.net.ftp.*;
Import sun.net.*;
Import java.applet.*;
Import java.io.*;
Import java.io.IOException;
Import Java.util.StringTokenizer;
Import sun.net.ftp.FtpClient;
Import java.util.ArrayList;

public class FTP extends Applet
{
FtpClient AFTP;
DataOutputStream outputs;
Telnetinputstream ins;
Telnetoutputstream outs;

int ch;
Public String A;
String hostname= "";
Private String Path = "/";

public static void Main (string[] args)
{
String hostname = "192.168.0.56";
int port = 2121;
String uid = "Lee";
String pwd = "Lee";
String Rwfiledir = "d:\\smsftp\\";//File directory

Connecting to an FTP server
FTP ft = new FTP ();
Ft.connect (RWFILEDIR,HOSTNAME,PORT,UID,PWD);

Download files
if (ft.aftp!= null) {
try {
Ft.getnamelist (Rwfiledir);
}catch (IOException e)
{
SYSTEM.OUT.PRINTLN ("Error downloading file:" +e);
}
}


Uploading files
if (ft.aftp!= null) {
String Sdir = rwfiledir + "subunsubfromsp\\";
File Fdir = new file (sdir);
String FileName = "";

for (int i=0;i FileName = Sdir + (fdir.list ()) [i];

Ft.uploadfile (Rwfiledir,filename);
}
System.out.println ("Successfully uploaded file:");
Ft.showfilecontents ("subunsubfromsp\\");
}

Delete file files that have been uploaded in the Subunsubfromsp directory
Ft.delefile (Rwfiledir);

Disconnect Server
Ft.stop (Rwfiledir);

}

Public ftpclient Connect (String rwfiledir,string hostname,int port,string uid,string pwd)
{
This.hostname = hostname;
SYSTEM.OUT.PRINTLN ("Connecting" +hostname+ ", please wait ...");
try{
AFTP = new FtpClient (hostname,port);
Aftp.login (UID,PWD);
Aftp.binary ();
Aftp.openportdataconnection ();
A = "Connect host:" +hostname+ "Success!";
System.out.println (a);
}
catch (Ftploginexception e) {
A= "Landing host:" +hostname+ failed! Please check that the username or password is correct: "+E;
System.out.println (a);
return false;
}
catch (IOException e) {
A= "Connection host:" +hostname+ failed! Please check the port is correct: "+E;
System.out.println (a);
return false;
}
catch (SecurityException e)
{
A= "No Permissions and Host:" +hostname+ connection! Check to see if you have access rights: "+E;
System.out.println (a);
return false;
}

Log (rwfiledir,a);
return AFTP;
}

public void Stop (String rwfiledir)
{
String message = "";
try {
if (aftp!=null) {
Aftp.closeserver ();
Message = "Disconnected from host" +hostname+ ";"
SYSTEM.OUT.PRINTLN (message);
Log (rwfiledir,message);
}
}
catch (IOException E)
{
message = "Disconnect from host" +hostname+ failed! " +e;
SYSTEM.OUT.PRINTLN (message);
Log (rwfiledir,message);
}
}


public boolean downloadFile (String rwfiledir,string filepathname) {
Boolean result=true;
String message = "";
if (AFTP!= null)
{
SYSTEM.OUT.PRINTLN ("Downloading the file" +filepathname+ ", please wait ...");
String badfile = filepathname.substring (Filepathname.length () -4,filepathname.length ());
String Badlog = filepathname.substring (Filepathname.length () -7,filepathname.length ());
String baddir = "";
if ((Badfile.compareto (". Bad")!= 0) && (Badlog.compareto (". Badlog")!= 0)) {
Baddir = "subunsubtosp\\";
}
else{
Baddir = "bad\\";
}
String Strdir = "subunsubtosp\\";
System.out.println (Rwfiledir + baddir + filepathname);
try{
FtpClient fc=new ftpclient ("192.168.0.56", 2121);
Fc.login ("Lee", "Lee");
int ch;
File fi = new file (Rwfiledir + baddir + filepathname);
AFTP.CD (Strdir);
Randomaccessfile getFile = new Randomaccessfile (FI, "RW");
Getfile.seek (0);
Telnetinputstream Fget=aftp.get (strdir+filepathname);
DataInputStream puts = new DataInputStream (fget);
while (ch = puts.read ()) >= 0) {
Getfile.write (CH);

}
S.delete ();

Fget.close ();
Getfile.close ();
Fc.closeserver ();

message = "Download" +filepathname+ "file to" +baddir + "directory success!";
SYSTEM.OUT.PRINTLN (message);
Log (rwfiledir,message);
}
catch (IOException e) {
message = "Download +filepathname+" file to "+baddir +" directory failed! " +e;
SYSTEM.OUT.PRINTLN (message);
Log (rwfiledir,message);
result = false;

}
}
else{
result = false;
}
return result;
}


public boolean uploadfile (String rwfiledir,string filepathname) {
Boolean result=true;
String message = "";
if (AFTP!= null)
{
System.out.println ("Uploading File" +filepathname+ ", please wait ...");

try{
String FG =new string ("\\subunsubfromsp\\");
int index = FILEPATHNAME.LASTINDEXOF (FG);
String filename = filepathname.substring (index+1);
File LocalFile = new file (filepathname);

Randomaccessfile sendFile = new Randomaccessfile (filepathname, "R");
//
Sendfile.seek (0);
Name Upload Temp_
filename = filename.substring (0,15) + "Temp_" +filename.substring (15,filename.length ());
Outs = Aftp.put (filename);
outputs = new DataOutputStream (outs);
while (Sendfile.getfilepointer () < Sendfile.length ())
{
ch = sendfile.read ();
Outputs.write (CH);
}

Rename (filename.substring (15,filename.length ()), filename.substring (20,filename.length ()));
Outs.close ();
Sendfile.close ();

message = "Upload" +filepathname+ "file success!";
SYSTEM.OUT.PRINTLN (message);
Log (rwfiledir,message);
}
catch (IOException e) {
message = "Upload" +filepathname+ "file failed!" +e;
SYSTEM.OUT.PRINTLN (message);
Log (rwfiledir,message);
result = false;

}
}
else{
result = false;
}
return result;
}

public void rename (String oldname,string newName) {

Aftp.renameto (Oldname,newname);
File old = new file (oldname); Oldname
File New = new file (newName); NewName
Aftp.renameto (NEW);
Boolean Old.renameto (File newName);
SYSTEM.OUT.PRINTLN (old);
System.out.println (NEW);

}

public static void Delefile (String rwfiledir) {
try {
Get TXT file in ReadFile directory
String Sdir = rwfiledir + "subunsubfromsp\\";
File Fdir = new file (sdir);
String FileName = "";
Int J = fdir.list (). length;

Number of files to delete in the System.out.println (sdir+ directory: +fdir.list (). length);
File file;
for (int i=0;i {
Delete txt file in Subunsubfromsp
FileName = Rwfiledir + "subunsubfromsp\\" + (Fdir.list ()) [0];
File = new file (FileName);
File.delete ();
System.out.println ("+filename+" file has been successfully deleted!) ");
}
//}
catch (IOException e) {
System.out.println ("Delete txt file error!");
E.printstacktrace ();
//}
}


public void Showfilecontents (String strdir)
{
StringBuffer buf = new StringBuffer ();
try {
AFTP.CD (Strdir);
Ins= aftp.list ();
while ((Ch=ins.read ()) >=0) {
Buf.append ((char) ch);
}

System.out.println (Buf.tostring ());

Ins.close ();
}
catch (IOException E)
{
}
}



Returns all files and folders in the current directory

Public ArrayList getfilelist () throws IOException {
BufferedReader dr = new BufferedReader (New InputStreamReader (Aftp.list ()));
ArrayList al = new ArrayList ();
String s = "";
while ((s = dr.readline ())!= null) {
Al.add (s);
}
Return al;
}

public void SetPath (String path) throws IOException {
if (AFTP = null)
This.path = path;
else {
AFTP.CD (path);
}
}

Returns the file name of the current directory

Public ArrayList getnamelist (String rwfiledir) throws IOException {

BufferedReader dr = new BufferedReader (New InputStreamReader (Aftp.namelist ("subunsubtosp\\"));
ArrayList al = new ArrayList ();
String s = "";
while ((s = dr.readline ())!= null) {
Al.add (s);
s = s.substring (13,s.length ());
Isfile (s);
DownloadFile (rwfiledir,s);
String strfiledelf = aftp.namelist ("subunsubtosp\\");
File Filedelf=new file (s);
Filedelf.delete ();
}
Return al;
System.out.println (Al.add (s));
}

Determine if a row of file information is a directory

public boolean isdir (String line) {
Return ((String) ParseLine (line). Get (0)). IndexOf ("D")!=-1;
}

public boolean isfile (String line) {
Return!isdir (line);
}

Handling the line information obtained by getfilelist

Private ArrayList ParseLine (String line) {
ArrayList S1 = new ArrayList ();
StringTokenizer st = new StringTokenizer (line, "");
while (St.hasmoretokens ()) {
S1.add (St.nexttoken ());
}
return s1;
}

Write Message Log
public static void log (String rwfiledir,string msg)
{
String message = "";
try {
Java.text.DateFormat df = new Java.text.SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Java.text.DateFormat Dflog = new Java.text.SimpleDateFormat ("YyyyMMdd");
Java.util.Date Date = new Java.util.Date ();
String datestr = Df.format (New java.util.Date ());
String Datelog = Dflog.format (New java.util.Date ());
String Datelog = datestr.substring (0,10);
Datelog = Datelog.replace ('-', ');

Generate a log file daily by date
FileWriter FWL = new FileWriter (Rwfiledir + "cmssftp" +datelog+ ". Log", true);
PrintWriter outl = new PrintWriter (FWL);
Outl.println (Datestr + "" + msg);
Outl.close ();
Fwl.close ();
}catch (IOException e) {
message = "Write log file Error!" +e;
E.printstacktrace ();
Log (rwfiledir,message);
SYSTEM.OUT.PRINTLN (message);
}
}
}





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.