CaptainKirk
asked on
Listing and retrieving files on a FTP directory.
Hi,
I have an interesting challenge. I need some code that will (using FTP) return a list of files in a directory, download said files, and delete said file. I have mastered FTP'ing files to a remote directory; now I need to figure out how to do the reverse. If more details are needed let me know.
Thanks,
P.S. I am currently using sun.net.ftp.FtpClient.
I have an interesting challenge. I need some code that will (using FTP) return a list of files in a directory, download said files, and delete said file. I have mastered FTP'ing files to a remote directory; now I need to figure out how to do the reverse. If more details are needed let me know.
Thanks,
P.S. I am currently using sun.net.ftp.FtpClient.
Rajendra, where did you copy the code from?
Hi,
That u have to find out.
That u have to find out.
Do you know what I call this?
CHEATING!
I think the captain would prefer to know more about the origin of the code. Imagine there was a copyright to it and you removed it. Then the captain will get into trouble, not you.
Thanks for listening.
CHEATING!
I think the captain would prefer to know more about the origin of the code. Imagine there was a copyright to it and you removed it. Then the captain will get into trouble, not you.
Thanks for listening.
Hi,
That u have to find out.
That u have to find out.
Hey, Rajendra, please give a sensible answer, if you prefer to answer at all. I might report you to Community Support...
ASKER
This is the "Captain",
Thankyou Rajendra for the code, however, I have to agree with dnoelpp. I will need to know the origin of the code in case of CopyRight. If you do not wish to disclose the source I will understand.
Thanks again,
Thankyou Rajendra for the code, however, I have to agree with dnoelpp. I will need to know the origin of the code in case of CopyRight. If you do not wish to disclose the source I will understand.
Thanks again,
Hi,
There is no CopyRight for the above code. You will find many sites which gives u the free code. It is your skill How u find out and implement according to your need?
There is no CopyRight for the above code. You will find many sites which gives u the free code. It is your skill How u find out and implement according to your need?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks alot!
The following code may help u.
import java.net.*;
import java.io.*;
import java.util.*;
// --------------------------
// Ftp class wrtiten based on RFC 959.
//
// The following commands based on RFC 959 have been implemented.
//
// CDUP - Change to Parent Directory
// SMNT - Structure Mount
// STOU - Store Unique
// RMD - Remove Directory
// MKD - Make Directory
// PWD - Print Directory
// SYST - System
// TYPE - Type, binary, ascii EBSIDC
// RETR - Retrieve a file
// CWD - Change working directory.
// NLST - Send directory listing.
// PORT - Set the port number.
// SITE - Retrieve site info from remote host.
// ABOR - Abort connection.
// LIST - Get a directory lising from remote host.
// STOR - Store a file on the target machine.
//
// < Ftp process diagram. Shows the flow of commands and
// < responses that are exchanged between the client and
// < remote host. Note: this does not support file
// < transfer between two remote hosts. The user of this
// < process must be logged in to the client side and
// < have the proper file permissions on both the remote
// < host and the client to be able to ftp files between
// < the client and server.
//
// -------------
// |/---------\|
// || User || --------
// ||Interface|<--->| User |
// |\----^----/| --------
// ---------- | | |
// |/------\| FTP Commands |/----V----\|
// ||Server|<----------------
// || PI || FTP Replies || PI ||
// |\--^---/| |\----^----/|
// | | | | | |
// -------- |/--V---\| Data |/----V----\| --------
// | File |<--->|Server|<-----------
// |System| || DTP || Connection || DTP || |System|
// -------- |\------/| |\---------/| --------
// ---------- -------------
//
// --------------------------
public class Ftp {
public static final int FTP_PORT = 21;
static int FTP_SUCCESSFULL = 1;
static int FTP_TRY_AGAIN = 2;
static int FTP_ERROR = 3;
public String m_strPassword = null;
public String m_strUserID = null;
public String m_strHost = null;
private String m_strCurrentCommand;
private boolean m_bPassiveMode = false;
private boolean m_bBinaryMode = false;
private boolean m_bReplyPending = false;
private Socket m_Socket = null;
public String m_strMsg;
public PrintWriter m_ServerSideOutput;
public InputStream m_ServerSideInput;
int nReturnCode;
protected Socket ServerSocket = null;
protected Vector serverResponse = new Vector(1);
public Ftp(String strHost, int iPort, String strUserId, String strPassword) throws IOException
{
m_strUserID = strUserId;
m_strPassword = strPassword;
openServer(strHost, iPort);
}
// --------------------------
// Use standard FTP port when port not specified.
// --------------------------
public Ftp(String strHost, String strUserId, String strPassword) throws IOException
{
m_strUserID = strUserId;
m_strPassword = strPassword;
openServer(strHost, FTP_PORT);
}
public Ftp(String strHost, int iPort) throws IOException
{
openServer(strHost, iPort);
}
// --------------------------
// Use standard FTP port when port not specified. Assume Anonymous login
// when no userid or password are specified.
// --------------------------
public Ftp(String strHost) throws IOException
{
m_strHost = strHost;
openServer(strHost, FTP_PORT);
}
// --------------------------
// APPEND (with create) (APPE)
//
// This command causes the server-DTP to accept the data
// transferred via the data connection and to store the data in
// a file at the server site. If the file specified in the
// pathname exists at the server site, then the data shall be
// appended to that file; otherwise the file specified in the
// pathname shall be created at the server site.
// --------------------------
// Append to an ascii file.
public BufferedWriter appendAscii(String strFileName) throws IOException
{
Socket s = openDataConnection("APPE " + strFileName);
return new BufferedWriter(new OutputStreamWriter(s.getOu
}
// Append to a binary file.
public BufferedOutputStream appendBinary(String strFileName) throws IOException
{
Socket s = openDataConnection("APPE " + strFileName);
return new BufferedOutputStream(s.get
}
// --------------------------
// RETRIEVE (RETR)
//
// This command causes the server-DTP to transfer a copy of the
// file, specified in the pathname, to the server- or user-DTP
// at the other end of the data connection. The status and
// contents of the file at the server site shall be unaffected.
// --------------------------
// Retrieve Ascii File
public BufferedReader getAsciiFile(String strFileName) throws IOException
{
Socket s = null;
try {
s = openDataConnection("RETR " + strFileName);
} catch (FileNotFoundException fileException) {fileException.printStackT
return new BufferedReader( new InputStreamReader(s.getInp
}
// Retrieve Binary File
public BufferedInputStream getBinary(String strFileName) throws IOException
{
Socket s = null;
try {
s = openDataConnection("RETR " + strFileName);
} catch (FileNotFoundException fileException) {fileException.printStackT
return new BufferedInputStream(s.getI
}
// --------------------------
// LIST (LIST)
//
// This command causes a list to be sent from the server to the
// passive DTP. If the pathname specifies a directory or other
// group of files, the server should transfer a list of files
// in the specified directory. If the pathname specifies a
// file then the server should send current information on the
// file. A null argument implies the user's current working or
// default directory. The data transfer is over the data
// connection in type ASCII or type EBCDIC.
// --------------------------
public BufferedReader list() throws IOException
{
Socket s = openDataConnection("LIST")
return new BufferedReader( new InputStreamReader(s.getInp
}
// --------------------------
// CHANGE WORKING DIRECTORY (CWD)
//
// This command allows the user to work with a different
// directory or dataset for file storage or retrieval without
// altering his login or accounting information. Transfer
// parameters are similarly unchanged. The argument is a
// pathname specifying a directory or other system dependent
// file group designator.
// --------------------------
public void cd(String remoteDirectory) throws IOException
{
sendCurrentCommandCheck("C
}
// --------------------------
// NAME LIST (NLST)
//
// This command causes a directory listing to be sent from
// server to user site. The pathname should specify a
// directory or other system-specific file group descriptor; a
// null argument implies the current directory. The server
// will return a stream of names of files and no other
// information. The data will be transferred in ASCII or
// EBCDIC type over the data connection as valid pathname
// strings separated by <CRLF> or <NL>. (Again the user must
// ensure that the TYPE is correct.) This command is intended
// to return information that can be used by a program to
// further process the files automatically. For example, in
// the implementation of a "multiple get" function.
// --------------------------
public BufferedReader nlist() throws IOException
{
Socket s = openDataConnection("NLST")
return new BufferedReader( new InputStreamReader(s.getInp
}
// --------------------------
// RENAME FROM (RNFR)
//
// This command specifies the old pathname of the file which is
// to be renamed. This command must be immediately followed by
// a "rename to" command specifying the new file pathname.
// --------------------------
public void rename(String oldFile, String newFile) throws IOException
{
sendCurrentCommandCheck("R
sendCurrentCommandCheck("R
}
// --------------------------
// STORE (STOR)
//
// This command causes the server-DTP to accept the data
// transferred via the data connection and to store the data as
// a file at the server site. If the file specified in the
// pathname exists at the server site, then its contents shall
// be replaced by the data being transferred. A new file is
// created at the server site if the file specified in the
// pathname does not already exist.
// --------------------------
// Store in Ascii format
public BufferedWriter putAscii(String strFileName) throws IOException
{
Socket s = openDataConnection("STOR " + strFileName);
return new BufferedWriter(new OutputStreamWriter(s.getOu
}
// Store in Binary format
public BufferedOutputStream putBinary(String strFileName) throws IOException
{
Socket s = openDataConnection("STOR " + strFileName);
return new BufferedOutputStream(s.get
}
// --------------------------
// TYPE (TYPE)
//
// The argument specifies the representation type as described
// in the Section on Data Representation and Storage. Several
// types take a second parameter. The first parameter is
// denoted by a single Telnet character, as is the second
// Format parameter for ASCII and EBCDIC; the second parameter
// for local byte is a decimal integer to indicate Bytesize.
// The parameters are separated by a <SP> (Space, ASCII code
// 32).
//
// The following codes are assigned for type:
//
// \ /
// A - ASCII | | N - Non-print
// |-><-| T - Telnet format effectors
// E - EBCDIC| | C - Carriage Control (ASA)
// / \
// I - Image
//
// L <byte size> - Local byte Byte size
// --------------------------
// Set user specifed mode.
public void setType(String strType) throws IOException
{
sendCurrentCommandCheck("T
}
// Set binary mode.
public void setBinaryMode() throws IOException
{
sendCurrentCommandCheck("T
m_bBinaryMode = true;
}
// Set ascii mode
public void setAsciiMode() throws IOException
{
sendCurrentCommandCheck("T
m_bBinaryMode = false;
}
// Set ebcdic mode, probably don't need to but what the heck.
public void setEbcdic() throws IOException
{
sendCurrentCommandCheck("T
m_bBinaryMode = true;
}
// --------------------------
// SITE PARAMETERS (SITE)
//
// This command is used by the server to provide services
// specific to his system that are essential to file transfer
// but not sufficiently universal to be included as commands in
// the protocol. The nature of these services and the
// specification of their syntax can be stated in a reply to
// the HELP SITE command.
// --------------------------
public void site(String strParms) throws IOException
{
sendCurrentCommandCheck("S
}
// --------------------------
// CHANGE TO PARENT DIRECTORY (CDUP)
//
// This command is a special case of CWD, and is included to
// simplify the implementation of programs for transferring
// directory trees between operating systems having different
// --------------------------
public void cdup() throws IOException {
sendCurrentCommandCheck("C
}
// --------------------------
//
// ABORT (ABOR)
//
// This command tells the server to abort the previous FTP
// service command and any associated transfer of data. The
// abort command may require "special action", as discussed in
// the Section on FTP Commands, to force recognition by the
// server. No action is to be taken if the previous command
// has been completed (including data transfer). The control
// connection is not to be closed by the server, but the data
// connection must be closed.
// --------------------------
public void abort() throws IOException
{
sendCurrentCommandCheck("A
}
// --------------------------
//
// MAKE DIRECTORY (MKD)
//
// This command causes the directory specified in the pathname
// to be created as a directory (if the pathname is absolute)
// or as a subdirectory of the current working directory (if
// the pathname is relative).
// --------------------------
public void mkdir(String strTemp) throws IOException
{
sendCurrentCommandCheck("M
}
// --------------------------
//
// DELETE (DELE)
//
// This command causes the file specified in the pathname to be
// deleted at the server site. If an extra level of protection
// is desired (such as the query, "Do you really wish to
// delete?"), it should be provided by the user-FTP process.
// --------------------------
public void delete(String strTemp) throws IOException
{
sendCurrentCommandCheck("D
}
// --------------------------
// PRINT WORKING DIRECTORY (PWD)
//
// This command causes the name of the current working
// directory to be returned in the reply. See Appendix II.
// --------------------------
public void pwd() throws IOException
{
sendCurrentCommandCheck("P
}
// --------------------------
// SYSTEM (SYST)
//
// This command is used to find out the type of operating
// system at the server. The reply shall have as its first
// word one of the system names listed in the current version
// of the Assigned Numbers document.
// --------------------------
public void syst() throws IOException
{
sendCurrentCommandCheck("S
}
// --------------------------
// REMOVE DIRECTORY (RMD)
//
// This command causes the directory specified in the pathname
// to be removed as a directory (if the pathname is absolute)
// or as a subdirectory of the current working directory (if
// the pathname is relative).
// --------------------------
public void rmdir(String strTemp) throws IOException
{
sendCurrentCommandCheck("R
}
// --------------------------
// This method will retrieve an Ascii text file from a remote.
//
// Parms: strFileName Full path to the Ascii text file on the remote host.
// --------------------------
// --------------------------
// PASSIVE (PASV)
//
// This command requests the server-DTP to "listen" on a data
// port (which is not its default data port) and to wait for a
// connection rather than initiate one upon receipt of a
// transfer command. The response to this command includes the
// host and port address this server is listening on.
// --------------------------
public void setPassiveMode(boolean mode) {
m_bPassiveMode = mode;
}
// --------------------------
// Parse the remote host response.
// --------------------------
public int readServerResponse() throws IOException {
int iTemp;
int continuingCode = -1;
int iCurrnetCode = -1;
StringBuffer replyBuf = new StringBuffer(32);
String strResponse;
try{
while (true) {
while ((iTemp = m_ServerSideInput.read()) != -1) {
if (iTemp == '\r') {
if ((iTemp = m_ServerSideInput.read()) != '\n')
replyBuf.append('\r');
}
replyBuf.append((char)iTem
if (iTemp == '\n')
break;
}
strResponse = replyBuf.toString();
replyBuf.setLength(0);
try {
iCurrnetCode = Integer.parseInt(strRespon
} catch (NumberFormatException e) {
iCurrnetCode = -1;
} catch (StringIndexOutOfBoundsExc
continue;
}
serverResponse.addElement(
if (continuingCode != -1) {
if (iCurrnetCode != continuingCode ||
(strResponse.length() >= 4 && strResponse.charAt(3) == '-')) {
continue;
} else {
continuingCode = -1;
break;
}
} else if (strResponse.length() >= 4 && strResponse.charAt(3) == '-') {
continuingCode = iCurrnetCode;
continue;
} else {
break;
}
}
}catch(Exception e){e.printStackTrace();}
return nReturnCode = iCurrnetCode;
}
public String receiveResponse() {
String strTemp = new String();
for(int i = 0;i < serverResponse.size();i++)
strTemp += serverResponse.elementAt(i
}
serverResponse = new Vector(1);
return strTemp;
}
public String receiveResponseWithNoReset
String s = new String();
for(int i = 0;i < serverResponse.size();i++)
s+=serverResponse.elementA
}
return s;
}
public void sendServer(String strCommand)
{
m_ServerSideOutput.println
}
public boolean serverConnectionOpen()
{
return ServerSocket != null;
}
// --------------------------
// --------------------------
protected int sendCurrentCommand(String strCommand) throws IOException
{
m_strCurrentCommand = strCommand;
int iReply;
if (m_bReplyPending) {
if (readResponse() == FTP_ERROR)
System.out.print("Error reading current pending reply\n");
}
m_bReplyPending = false;
do {
sendServer(strCommand);
iReply = readResponse();
} while (iReply == FTP_TRY_AGAIN);
return iReply;
}
// --------------------------
// Check the current command for validity.
// --------------------------
protected void sendCurrentCommandCheck(St
{
if (sendCurrentCommand(strCom
throw new FtpProtocolException(strCo
}
}
// --------------------------
// LOGOUT (QUIT)
//
// This command terminates a USER and if file transfer is not
// in progress, the server closes the control connection. If
// file transfer is in progress, the connection will remain
// open for result response and the server will then close it.
// If the user-process is transferring files for several USERs
// but does not wish to close and then reopen connections for
// each, then the REIN command should be used instead of QUIT.
//
// An unexpected close on the control connection will cause the
// server to take the effective action of an abort (ABOR) and a
// logout (QUIT).
// --------------------------
public void exitServer() throws IOException
{
if (serverConnectionOpen())
{
sendCurrentCommand("QUIT")
if (! serverConnectionOpen())
{
return;
}
ServerSocket.close();
ServerSocket = null;
m_ServerSideInput = null;
m_ServerSideOutput = null;
}
}
// --------------------------
// Parse remote host response for errors.
//
// Reply Codes by Function Groups
//
// 110 Restart marker reply.
// In this case, the text is exact and not left to the
// particular implementation; it must read:
// MARK yyyy = mmmm
// Where yyyy is User-process data stream marker, and mmmm
// server's equivalent marker (note the spaces between markers
// and "=").
// 120 Service ready in nnn minutes.
// 125 Data connection already open; transfer starting.
// 150 File status okay; about to open data connection.
// 200 Command okay.
// 202 Command not implemented, superfluous at this site.
// 211 System status, or system help reply.
// 212 Directory status.
// 213 File status.
// 214 Help message.
// On how to use the server or the meaning of a particular
// non-standard command. This reply is useful only to the
// human user.
// 215 NAME system type.
// Where NAME is an official system name from the list in the
// Assigned Numbers document.
// 220 Service ready for new user.
// 221 Service closing control connection.
// Logged out if appropriate.
// 225 Data connection open; no transfer in progress.
// 226 Closing data connection.
// Requested file action successful (for example, file
// transfer or file abort).
// 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
// 230 User logged in, proceed.
// 250 Requested file action okay, completed.
// 257 "PATHNAME" created.
//
// 331 User name okay, need password.
// 332 Need account for login.
// 350 Requested file action pending further information.
//
// 421 Service not available, closing control connection.
// This may be a reply to any command if the service knows it
// must shut down.
// 425 Can't open data connection.
// 426 Connection closed; transfer aborted.
// 450 Requested file action not taken.
// File unavailable (e.g., file busy).
// 451 Requested action aborted: local error in processing.
// 452 Requested action not taken.
// Insufficient storage space in system.
// 500 Syntax error, command unrecognized.
// This may include errors such as command line too long.
// 501 Syntax error in parameters or arguments.
// 502 Command not implemented.
// 503 Bad sequence of commands.
// 504 Command not implemented for that parameter.
// 530 Not logged in.
// 532 Need account for storing files.
// 550 Requested action not taken.
// File unavailable (e.g., file not found, no access).
// 551 Requested action aborted: page type unknown.
// 552 Requested file action aborted.
// Exceeded storage allocation (for current directory or
// dataset).
// 553 Requested action not taken.
// File name not allowed.
// --------------------------
protected int readResponse() throws IOException
{
nReturnCode = readServerResponse();
switch (nReturnCode / 100)
{
case 1:
m_bReplyPending = true;
case 2: // Do nothing, pass through.
case 3:
return FTP_SUCCESSFULL;
case 4:
if (nReturnCode == 421)
{
throw new FtpConnectException("Conne
}
if (nReturnCode == 425)
{
throw new FtpConnectException("Can't
}
if (nReturnCode == 426)
{
throw new FtpConnectException("Conne
}
if (nReturnCode == 421)
{
throw new FtpConnectException("Conne
}
if (nReturnCode == 421)
{
throw new FtpConnectException("Conne
}
return FTP_ERROR;
case 5:
if (nReturnCode == 530)
{
if (m_strUserID == null)
{
throw new FtpLoginException("No userid found");
}
else if (m_strPassword == null) {
throw new FtpLoginException("No password was provided");
}
return FTP_ERROR;
}
if (nReturnCode == 550)
{
if (!m_strCurrentCommand.star
throw new FileNotFoundException(m_st
else
throw new FtpLoginException("Bad password!");
}
if (nReturnCode == 532)
{
throw new FtpLoginException("No account defined for user");
}
}
return FTP_ERROR;
}
// --------------------------
//
// --------------------------
protected Socket openDataConnection(String strCommand) throws IOException
{
ServerSocket portSocket = null;
int iPort = 0;
String portCmd;
int shift;
InetAddress myAddress = InetAddress.getLocalHost()
byte addr[] = myAddress.getAddress();
String ipaddress;
IOException e;
if (this.m_bPassiveMode) {
try {
receiveResponse();
if (sendCurrentCommand("PASV"
e = new FtpProtocolException("PASV
throw e;
}
String reply = receiveResponseWithNoReset
reply = reply.substring(reply.last
StringTokenizer st = new StringTokenizer(reply, ",");
String[] nums = new String[6];
int i = 0;
while(st.hasMoreElements()
try
{
nums[i] = st.nextToken();
i++;
}
catch(Exception all) {
all.printStackTrace();
}
}
// Format ip address
ipaddress = nums[0]+"."+nums[1]+"."+nu
try
{
int firstbits = Integer.parseInt(nums[4]) << 8;
int lastbits = Integer.parseInt(nums[5]);
iPort = firstbits + lastbits;
}
catch(Exception b) {
b.printStackTrace();
}
if((ipaddress != null) && (iPort != 0))
{
m_Socket = new Socket(ipaddress, iPort);}
else {
e = new FtpProtocolException("PASV
throw e;
}
if (sendCurrentCommand(strCom
{
e = new FtpProtocolException(strCo
throw e;
}
}
catch (FtpProtocolException fpe) {
portCmd = "PORT ";
for (int i = 0; i < addr.length; i++) {
portCmd = portCmd + (addr[i] & 0xFF) + ",";
}
try
{
portSocket = new ServerSocket(20000);
portCmd = portCmd + ((portSocket.getLocalPort(
+ (portSocket.getLocalPort()
if (sendCurrentCommand(portCm
{
e = new FtpProtocolException("PORT
throw e;
}
if (sendCurrentCommand(strCom
{
e = new FtpProtocolException(strCo
throw e;
}
m_Socket = portSocket.accept();
}
finally {
if(portSocket != null)
portSocket.close();
}
m_Socket = portSocket.accept();
portSocket.close();
}
}
else {
portCmd = "PORT ";
for (int i = 0; i < addr.length; i++) {
portCmd = portCmd + (addr[i] & 0xFF) + ",";
}
try {
portSocket = new ServerSocket(20000);
portCmd = portCmd + ((portSocket.getLocalPort(
+ (portSocket.getLocalPort()
if (sendCurrentCommand(portCm
{
e = new FtpProtocolException("PORT
throw e;
}
if (sendCurrentCommand(strCom
e = new FtpProtocolException(strCo
throw e;
}
m_Socket = portSocket.accept();
}
finally {
if(portSocket != null)
portSocket.close();
}
m_Socket = portSocket.accept();
portSocket.close();
}
return m_Socket;
}
// --------------------------
// Open up a connection with the remote host. Define the Output buffer
// and input buffers.
// --------------------------
public void openServer(String strHost) throws IOException, UnknownHostException {
int iPort = FTP_PORT;
if (ServerSocket != null)
exitServer();
ServerSocket = new Socket(strHost, FTP_PORT);
m_ServerSideOutput = new PrintWriter(new BufferedOutputStream(Serve
m_ServerSideInput = new BufferedInputStream(Server
}
// --------------------------
// Login in to the remote host.
// --------------------------
public void login(String strUser) throws IOException {
if (!serverConnectionOpen())
throw new FtpLoginException("Current
this.m_strUserID = strUser;
if (sendCurrentCommand("USER " + strUser) == FTP_ERROR)
throw new FtpLoginException("Error: Invalid Username.\n");
}
// --------------------------
// Login in to the remote host.
// --------------------------
public void login(String strUser, String strPassword) throws IOException {
if (!serverConnectionOpen())
throw new FtpLoginException("Error: not connected to host.\n");
this.m_strUserID = strUser;
this.m_strPassword = strPassword;
if (sendCurrentCommand("USER " + strUser) == FTP_ERROR)
throw new FtpLoginException("Error: User not found.\n");
if (m_strPassword != null && sendCurrentCommand("PASS " + strPassword) == FTP_ERROR)
throw new FtpLoginException("Error: Bad Password.\n");
}
// --------------------------
// Login in to the remote host.
// --------------------------
public void login() throws IOException {
if (!serverConnectionOpen())
throw new FtpLoginException("Error: not connected to host.\n");
if(this.m_strUserID == null)
this.m_strUserID = "anonymous";
if(this.m_strPassword == null)
this.m_strPassword = "tempest@isrglobal.com";
if (sendCurrentCommand("USER " + this.m_strUserID) == FTP_ERROR)
throw new FtpLoginException("Error: User not found.\n");
if (m_strPassword != null && sendCurrentCommand("PASS " + this.m_strPassword) == FTP_ERROR)
throw new FtpLoginException("Error: Bad Password.\n");
}
// --------------------------
// Open socket connect to the remote host.
// --------------------------
public void openServer(String strHost, int iPort) throws IOException, UnknownHostException {
if (ServerSocket != null)
exitServer();
ServerSocket = new Socket(strHost, iPort);
m_ServerSideOutput = new PrintWriter(new BufferedOutputStream(Serve
true);
m_ServerSideInput = new BufferedInputStream(Server
if (readResponse() == FTP_ERROR)
throw new FtpConnectException("Welco
}
// --------------------------
// Login to remote host and retreive the indicated file from the
// remote host.
// --------------------------
public void GetAsciiFile(String strFileName) throws IOException
{
System.out.print(receiveRe
setPassiveMode(true);
//////////////////////////
setAsciiMode();
System.out.println(m_strCu
System.out.print(receiveRe
BufferedReader fInputFile = getAsciiFile(strFileName);
System.out.println(m_strCu
System.out.print(receiveRe
PrintWriter fOutPutFile = new PrintWriter(new BufferedWriter(new FileWriter(strFileName)));
int i;
char c[] = new char[4096];
while ((i = fInputFile.read(c)) != -1)
fOutPutFile.write(c,0,i);
fInputFile.close();
fOutPutFile.close();
System.out.print(receiveRe
}
// --------------------------
// Login to remote host and retreive the indicated file from the
// remote host.
// --------------------------
public void GetBinaryFile(String strFileName) throws IOException
{
System.out.print(receiveRe
setPassiveMode(true);
//////////////////////////
setBinaryMode();
System.out.println(m_strCu
System.out.print(receiveRe
BufferedInputStream fInputFile = getBinary(strFileName);
System.out.println(m_strCu
System.out.print(receiveRe
BufferedOutputStream fOutputFile = new BufferedOutputStream(new FileOutputStream(strFileNa
int i;
byte b[] = new byte[4096];
while ((i = fInputFile.read(b)) != -1)
fOutputFile.write(b,0,i);
fInputFile.close();
fOutputFile.close();
System.out.print(receiveRe
}
// --------------------------
// Login to remote host and retreive the indicated file from the
// remote host.
// --------------------------
public void SendBinaryFile(String strFileName) throws IOException
{
System.out.print(receiveRe
setPassiveMode(true);
//////////////////////////
String localFile = strFileName;
setBinaryMode();
System.out.println(m_strCu
BufferedOutputStream fOutputFile = putBinary(localFile);
System.out.println(m_strCu
System.out.print(receiveRe
BufferedInputStream fInputFile = new BufferedInputStream(new FileInputStream(localFile)
int j;
byte b[] = new byte[1024];
while ((j = fInputFile.read(b)) != -1)
fOutputFile.write(b,0,j);
fInputFile.close();
fOutputFile.flush();
fOutputFile.close();
System.out.print(receiveRe
// Shut down
exitServer();
System.out.println(m_strCu
System.out.print(receiveRe
}
// --------------------------
// Login to remote host and retreive the indicated file from the
// remote host.
// --------------------------
public void SendAsciiFile(String strFileName) throws IOException
{
System.out.print(receiveRe
setPassiveMode(true);
//////////////////////////
String strLocalFile = strFileName;
setAsciiMode();
System.out.println(m_strCu
BufferedWriter fOutputFile = putAscii(strLocalFile);
System.out.println(m_strCu
System.out.print(receiveRe
BufferedInputStream fInputFile = new BufferedInputStream(new FileInputStream(strLocalFi
int j;
while ((j = fInputFile.read()) != -1)
{
fOutputFile.write(j);
}
fInputFile.close();
fOutputFile.flush();
fOutputFile.close();
System.out.print(receiveRe
// Shut down
exitServer();
System.out.println(m_strCu
System.out.print(receiveRe
}
// --------------------------
// For testing purposes.
// --------------------------
public static void main (String args []) throws IOException
{
// Sample to send an ascii file.
Ftp clsFtp = new Ftp("203.129.237.74");
clsFtp.login("root","melstar");
//clsFtp.SendAsciiFile("test.txt");
// Sample to receive a binary file.
// Ftp clsFtp = new Ftp("203.129.237.74","root
// Ftp clsFtp = new Ftp("www.cisco.com");
// clsFtp.login();
// clsFtp.setPassiveMode(true);
clsFtp.cd("opt");
clsFtp.cd("test");
// clsFtp.cd("catalyst");
// clsFtp.cd("1900-standard");
// String strPath = "pub/lan/catalyst/1900-sta
//File flFileName = new File("pub/lan/catalyst/190
//String strTest = flFileName.getParent();
//String strTest2 = flFileName.getName();
//String strParentDir = flFileName.getParent();
//if(strParentDir != null)
// clsFtp.cd("pub/lan/catalyst/1900-
//String strFileName = "pub/lan/catalyst/1900-sta
String strFileName = "alphabets.txt";
System.out.print(strFileNa
clsFtp.GetBinaryFile(strFileName);
// --------------------------
// Sample, retrieve a directory listing from the host
// --------------------------
/*
Ftp clsFtp = new Ftp("203.129.237.74");
clsFtp.login("root","melstar");
clsFtp.setPassiveMode(true);
try {
BufferedReader myBuffer = clsFtp.list();
BufferedOutputStream fOutputFile =
new BufferedOutputStream(new FileOutputStream("testfile
int j;
char c[] = new char[1024];
while((j = myBuffer.read()) != -1)
{
fOutputFile.write(j);
}
}
catch (Exception e) {
System.out.println("Failed
}
*/
// --------------------------
// Sample, create a directory on the remote host.
// --------------------------
/*
Ftp clsFtp = new Ftp("203.129.237.74");
clsFtp.login("root","melstar");
clsFtp.setPassiveMode(true);
try
{
clsFtp.mkdir("Talon");
}
catch (Exception e) {
System.out.println("Failed
}
*/
// --------------------------
// Sample, remove a directory on the remote host.
// --------------------------
/*
Ftp clsFtp = new Ftp("203.129.237.74");
clsFtp.login("root","melstar");
clsFtp.setPassiveMode(true);
try
{
clsFtp.rmdir("Talon");
}
catch (Exception e) {
System.out.println("Failed
ckdkdkdkd }
*/
// --------------------------
// Sample, change directory on the remote host.
// --------------------------
/*
Ftp clsFtp = new Ftp("203.129.237.74");
clsFtp.login("root","melstar");
clsFtp.setPassiveMode(true);
try
{
clsFtp.cd("opt/test");
clsFtp.pwd();
}
catch (Exception e) {
System.out.println("Failed
}
*/
}
}
class FtpProtocolException extends IOException {
FtpProtocolException(Strin
super(s);
}
}
class FtpConnectException extends FtpProtocolException {
FtpConnectException(String
super(s);
}
}
class FtpLoginException extends FtpProtocolException {
FtpLoginException(String s) {
super(s);
}
}