1)使用DOS的FTP.EXE
package powerftp;
import java.io.*;
public class FTPTest{
String user = "gamlty";
String passwd = "gamlty";
String server = "172.16.26.2";
int port = 21;
String remoteFile = "/anonymous/testput.pdf";
String localFile = "e:\\ftpbean\\install.pdf";
PrintWriter pw = null;
BufferedReader bs = null;
public FTPTest() {
try {
//String path = System.getProperty("user.dir");
String path = "e:";
}
catch(Exception e) {
e.printStackTrace();
}
}
private void writeParam(){
try {
pw = new PrintWriter(new FileOutputStream("e:\\ftp_in.dat"));
pw.println("open");
pw.println(server);
pw.println(user);
pw.println(passwd);
pw.println("binary");
pw.println("put");
pw.println(localFile);
pw.println(remoteFile);
pw.println("quit");
pw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public int exec() {
int ret = 1;
try {
writeParam();
String line = new String();
File dir = new File("e:\\");
String[] cmd = new String[2];
cmd[0] = "ftp.exe";
cmd[1] = "-s:ftp_in.dat";
Process p = Runtime.getRuntime().exec(cmd,null,dir);
BufferedReader m_es = new BufferedReader(new InputStreamReader(p.getErrorStream()));
if((line = m_es.readLine())!= null){
System.out.println(line);
ret = -1;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static void main(String[] args){
try {
FTPTest test = new FTPTest();
int ret = test.exec();
if(ret==0) System.out.println("FTP work OK");
else System.out.println("FTP work Faild");
}
catch(Exception e) {
e.printStackTrace();
}
}
/** e:\\ftp.dat included text
open 172.16.26.2
gamlty
gamlty
put e:\ftpbean\install.pdf /anonymous/testput.pdf
quit
*/
}
2)使用sun.net.ftp.*包
package powerftp;
import java.io.*;
import sun.net.ftp.*;
import sun.net.*;
import java.util.*;
public class SunFtp {
private String server = null;
private int port = 21;
private String user = "anonymous";
private String passwd = "";
private String remoteFile = null;
private String localFile = null;
// private String remotePath = null;
// private String localPath = null;
private String SYSTEM_CONFIG_FILE = "ftp.conf";
private boolean isConfig = false;
private String SERVER_KEY = "FTPSERVER";
private String PORT_KEY = "FTPPORT";
private String USER_KEY = "FTPUSER";
private String PASSWD_KEY = "FTPPASSWD";
Properties config = new Properties();
public SunFtp() {
}
public void init(){
try{
config.load( new FileInputStream(SYSTEM_CONFIG_FILE));
server = config.getProperty(SERVER_KEY);
port = Integer.parseInt(config.getProperty(PORT_KEY));
user = config.getProperty(USER_KEY);
passwd = config.getProperty(PASSWD_KEY);
}catch(Exception e){
System.out.print(e.getMessage());
}
}
public void setConfig(boolean b){
isConfig = b;
}
public void setServer(String srv,int no){
server = srv;
port = no;
}
public void setLogin(String usr,String psw){
user = usr;
passwd = psw;
}
public void setRemoteFile(String file){
remoteFile = file;
}
public void setLocalFile(String file){
localFile = file;
}
public String doFtpHandle(){
try {
FtpClient client = new FtpClient();
if(isConfig) init();
if(server == null) return "サーバの名前はありません";
if(remoteFile == null) return "サーバファイル名前はありません";
if(localFile == null) return "ローカルファイル名前はありません";
client.openServer(server,port);
client.login(user,passwd);
client.binary();
TelnetOutputStream out = client.put(remoteFile);
File file_in= new File(localFile);
DataInputStream is= new DataInputStream(new FileInputStream(file_in));
byte[] bytes = new byte[is.available()];
is.readFully(bytes);
is.close();
out.write(bytes);
out.close();
client.closeServer() ;
return "Upload OK";
} catch (Exception e) {
System.out.println(e.getMessage());
return e.getMessage();
}
}
public static void main(String[] args){
try {
SunFtp work = new SunFtp();
work.setConfig(true);
//work.setServer("172.16.26.2",21);
//work.setLogin("gamlty","gamlty");
work.setRemoteFile("level_1/level_2/level_3/test.pdf");
//work.setRemoteFile("test.pdf");
work.setLocalFile("E:\\ftpbean\\install.pdf");
String ret = work.doFtpHandle();
System.out.println("DEBUG " + ret);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
3)使用第三方包
package powerftp;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
import java.io.*;
import java.util.*;
public class DOFTP {
private String server = null;
private int port = 21;
private String user = "anonymous";
private String passwd = "";
private String remoteFile = null;
private String localFile = null;
// private String remotePath = null;
// private String localPath = null;
private String reponse = null;
private int repCode = 0;
private String SYSTEM_CONFIG_FILE = "ftp.conf";
private boolean isConfig = false;
private String SERVER_KEY = "FTPSERVER";
private String PORT_KEY = "FTPPORT";
private String USER_KEY = "FTPUSER";
private String PASSWD_KEY = "FTPPASSWD";
Properties config = new Properties();
public DOFTP() {
}
public void init(){
try{
config.load( new FileInputStream(SYSTEM_CONFIG_FILE));
server = config.getProperty(SERVER_KEY);
port = Integer.parseInt(config.getProperty(PORT_KEY));
user = config.getProperty(USER_KEY);
passwd = config.getProperty(PASSWD_KEY);
}catch(Exception e){
System.out.print(e.getMessage());
}
}
public void setConfig(boolean b){
isConfig = b;
}
public void setServer(String srv,int no){
server = srv;
port = no;
}
public void setLogin(String usr,String psw){
user = usr;
passwd = psw;
}
public void setRemoteFile(String file){
remoteFile = file;
}
public void setLocalFile(String file){
localFile = file;
}
public String DoFtpHandle(){
try{
if(isConfig) init();
FTPBean ftp = new FTPBean(true);
if(server == null) return "サーバの名前はありません";
ftp.setRemote(server,port);
boolean b = ftp.login(user,passwd);
if(b){
if(remoteFile == null) return "サーバファイル名前はありません";
if(localFile == null) return "ローカルファイル名前はありません";
b = ftp.storeFile(remoteFile,localFile,ftp.BINARY);
repCode = ftp.getLastResponseCode();
if(repCode != 226)
return ftp.getLastResponseDesc();
ftp.logout();
return "Upload OK";
}
else{
return ftp.getLastResponseDesc();
}
}catch(Exception e){
e.printStackTrace();
return e.getMessage();
}
}
public static void main(String[] args) {
try {
DOFTP work = new DOFTP();
work.setConfig(true);
//work.setServer("172.16.26.2",21);
//work.setLogin("gamlty","gamlty");
work.setRemoteFile("level_1/level_2/level_3/test.pdf");
//work.setRemoteFile("test.pdf");
work.setLocalFile("E:\\ftpbean\\install.pdf");
String ret = work.DoFtpHandle();
System.out.println("DEBUG " + ret);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
package powerftp;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;
import java.util.Vector;
/**
* FTPBean provides a consistent interface to an FTP Server. It provides
* all command submission, reponse handling and file transfer functions
* for the user, removing the tiresome task of error checking.
*<p>
* The FTPBean connects to the FTP server when instantiated, and is
* instantly ready for command submission or file transfer.
*<p>
* File transfers are handled through a different dataport than
* the communications port, and is determined using the PASV command.
*<p>
* Typical use of the FTPBean to transfer a file would be programmed
* as such:
*<blockquote>
* try {<br>
* FTPBean remote = new FTPBean(getCodeBase().getHost(), 21, "myName", "myPassword");<br>
* remote.setDirectory("my/directory");<br>
* remote.storeFile("remotefilename.ext", "localfile.ext", FTPBean.ASCII);<br>
* remote.logout();<br>
* }<br>
* catch(FTPException ftp) {<br>
* System.out.println("Error occured during file transmission:\r\n" + ftp.getMessage());<br>
* }<br>
* </blockquote>
*
* As you can see, the entire process can be handled using only one try/catch
* loop. With all possible errors being extended by FTPException.<p>
*/
public class FTPBean implements Serializable{
/**
* The socket used for client/server communication.
*/
private Socket ftpSocket;
/**
* The socket used for file transfer. This socket is located using the
* getDataSocket() method during FTPBean initialization.
*/
private Socket dataSocket;
/**
* The OutputStream used to send commands to the FTP Server.
*/
private PrintStream output;
/**
* The InputStream used to read FTP Server responses.
*/
private BufferedReader input;
/**
* The OutputStream used to write files to the FTP Server.
*/
private OutputStream dataStream;
/**
* The last reponse received from the FTP Server.
*/
private String lastreply = "";
/**
* boolean that holds login status.
*/
private boolean login_status = false;
/**
* boolean that holds verbose status. Setting this to true
* will send all FTP commands and responses to System.out
*/
private boolean verbose;
/**
* Static variable used to define ASCII content.
*/
public static final int ASCII = 0;
/**
* Static variable used to define BINARY content.
*/
public static final int BINARY = 1;
/**
* This no argument constructor creates an initially unlogged FTPBean.
* Before it can be used for file transfer, the {@link #setRemote(String, int) setRemote}
* and {@link #login(String, String) login} methods must be called.
*/
public FTPBean(boolean verbose) {
this.verbose = verbose;
}
/**
* This constructor creates an FTPBean with the initial socket connection
* already established. Before it can be used for file transfer, the
* {@link #login(String, String) login} method must be called.
* <p>
* @throws FTPException If an error code is received from the FTP Server during processing.
*/
public FTPBean(String server, int port, boolean verbose) throws FTPException{
try {
this.verbose = verbose;
ftpSocket = new Socket(server, port);
output = new PrintStream(ftpSocket.getOutputStream(), true);
input = new BufferedReader(new InputStreamReader(ftpSocket.getInputStream()));
if (!((input.readLine()).substring(0, 3)).equals("220"))
throw new FTPException("Server rejected connection:\n" + server + ":" + port);
}
catch(UnknownHostException uhe) {
throw new FTPException(uhe.getMessage());
}
catch(IOException ioe) {
throw new FTPException(ioe.getMessage());
}
}
/**
* This constructor for the FTPBean provides all login and dataSocket
* functions during initialization.
*
* @param
* server
* The string representation of the FTP host. (From an applet this will almost
* always be obtained using the Applet.getCodeBase().getHost() method.)
* @param
* port
* The FTP port of the Host server. (Usually 21).
*@param
* username
* The FTP login name to be used.
*@param
* password
* The FTP password that correlates to the FTP login name.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public FTPBean(String server, int port, String username, String password, boolean verbose) throws FTPException {
try {
this.verbose = verbose;
ftpSocket = new Socket(server, port);
output = new PrintStream(ftpSocket.getOutputStream(), true);
input = new BufferedReader(new InputStreamReader(ftpSocket.getInputStream()));
if (!((lastreply = input.readLine()).substring(0, 3)).equals("220"))
throw new FTPException("Server rejected connection:\n" + server + ":" + port);
if (! submitCommand("USER " + username))
throw new FTPException("Username " + username + " not accepted.");
if (! submitCommand("PASS " + password))
throw new FTPException("Password " + password + " not accepted.");
login_status = true;
}
catch(UnknownHostException uhe) {
throw new FTPException(uhe.getMessage());
}
catch(IOException ioe) {
throw new FTPException(ioe.getMessage());
}
catch(FTPException ftpe) {
throw ftpe;
}
}
/**
* This method sets the remote server and port number, creating the
* required input and output streams for command submission and reads
* connection reponse from server and puts the reponse in the lastreply
* String variable.
*<p>
* @param
* server The String representation of the FTP Server Host (in an Applet
* this value will almost always be obtained through Applet.getCodeBae().getHost()).
* @param
* port The FTP port of the remote server (usually 21).
*
* @return
* True if the server connection was accepted or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean setRemote(String server, int port) throws FTPException {
try {
ftpSocket = new Socket(server, port);
output = new PrintStream(ftpSocket.getOutputStream(), true);
input = new BufferedReader(new InputStreamReader(ftpSocket.getInputStream()));
if (!((lastreply = input.readLine()).substring(0, 3)).equals("220"))
return false;
return true;
}
catch(UnknownHostException uhe) {
throw new FTPException(uhe.getMessage());
}
catch(IOException ioe) {
throw new FTPException(ioe.getMessage());
}
}
/**
* This method attempts to login in to the remote FTP server using the
* supplied username and password arguments.
*<p>
*<b> NOTE:</b> This method must be preceeded with a successful call to
* {@link #setRemote(String, int) setRemote}<p>
*
* @param
* username FTP login name
* @param
* password FTP password
*
* @return
* True if the login was accepted or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean login(String username, String password) throws FTPException {
try {
if (! submitCommand("USER " + username))
return false;
if (! submitCommand("PASS " + password))
return false;
login_status = true;
return login_status;
}
catch(FTPException ftpe) {
throw ftpe;
}
}
/**
* This method performs the required logging out functions.
* <p>
* @throws FTPException If an error code is received during logout.
*/
public void logout() throws FTPException {
try {
if (! submitCommand("QUIT"))
throw new FTPException("Error during QUIT command");
if (dataStream != null) {
dataStream.flush();
dataStream.close();
}
if (output != null) {
output.flush();
output.close();
}
if (input != null)
input.close();
if (dataSocket != null)
dataSocket.close();
if (ftpSocket != null)
ftpSocket.close();
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
/**
* This method transmits the PASV command to request a non-default
* dataport for use in transmitting files to the remote server.<p>
* @return Socket Socket used to transmit file.
*<p>
* @throws FTPException If an exception occurs during receipt of port
* number
*/
private Socket setDataSocket() throws FTPException {
try {
if (verbose)
System.out.println("Command: PASV");
output.print("PASV\r\n");
String reply = input.readLine();
if (verbose)
System.out.println("Response: " + reply + "\r\n");
return getDataSocket(reply);
}
catch(IOException ioe) {
throw new FTPException(ioe.getMessage());
}
}
/**
* Private method that prompts the FTP server for a data port for use
* in transferring files.
*<p>
* This method should not be used directly and is called by the FTPBean
* constructor.
*<p>
* @parameter String The server reponse line that contains the dataport information.
*
* @return
* Socket to be used for file transfer.
*
* @throws
* IOException
*/
private Socket getDataSocket(String reply) throws IOException{
StringTokenizer st = new StringTokenizer(reply, ",");
String[] parts = new String[6]; // parts, incl. some garbage
int i = 0; // put tokens into String array
while(st.hasMoreElements()) {
// stick pieces of host, port in String array
try {
parts[i] = st.nextToken();
i++;
} catch(NoSuchElementException nope){
nope.printStackTrace();
}
} // end getting parts of host, port
String[] diggies = new String[3];
for(int j = 0; j < 3; j++) {
diggies[j] = parts[0].substring(parts[0].length() - (j + 1),parts[0].length() - j); // next: digit or character?
if(!Character.isDigit(diggies[j].charAt(0)))
diggies[j] = "";
}
parts[0] = diggies[2] + diggies[1] + diggies[0];
String[] porties = new String[3];
for(int k = 0; k < 3; k++) {
if((k + 1) <= parts[5].length())
porties[k] = parts[5].substring(k, k + 1);
else porties[k] = "FOOBAR"; // definitely not a digit!
if(!Character.isDigit(porties[k].charAt(0)))
porties[k] = "";
} // Have to do this one in order, not inverse order
parts[5] = porties[0] + porties[1] + porties[2];
String ip = parts[0]+"."+parts[1]+"."+parts[2]+"."+parts[3];
int port = -1;
try { // Get first part of port, shift by 8 bits.
int big = Integer.parseInt(parts[4]) << 8;
int small = Integer.parseInt(parts[5]);
port = big + small; // port number
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
}
if((ip != null) && (port != -1)) {
Socket dsock = new Socket(ip, port);
return dsock;
}
else throw new IOException();
}
/**
* A private method used to submit commands to the FTP server.
* This method is called internally and should not be used
* directly.<p>
*
* @return
* True or False where:
* True = An approved reponse was received after command submission.
* False = An unapproved reponse was received after command submission.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*
* @see String#getLastResponse() getLastResponse
*/
private boolean submitCommand(String command) throws FTPException {
try {
if (verbose)
System.out.println("Command: " + command);
output.print(command + "\r\n");
output.flush();
lastreply = input.readLine();
// if(command.indexOf("STOR")!=-1)
// lastreply = input.readLine();
if (lastreply.charAt(3) == '-') { // Multi-line reply
String response = lastreply.substring(0, 3);
String line = "";
while ((line = input.readLine()).charAt(3) == '-')
lastreply += ("\r\n" + line);
lastreply += ("\r\n" + line);
}
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
if (lastreply.charAt(0) == '4' || lastreply.charAt(0) == '5')
return false;
else
return true;
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
/**
* This method returns the last reponse received from the FTP Server.
* This method is useful after receipt of an FTPException, to view
* the server's actual rejected response.
*<p>
* @return
* The last reponse from the FTP Server.
*/
public String getLastResponse() {
return lastreply;
}
public int getLastResponseCode() {
int ret = 0;
try{
String code = lastreply.substring(0,3);
ret = Integer.parseInt(code);
}catch(Exception e){
return 0;
}
return ret;
}
public String getLastResponseDesc() {
String desc = lastreply.substring(lastreply.indexOf(" "));
return desc;
}
/**
* Sets the remote directory on the FTP server.
*
* @param
* directory The desired remote directory.
*
* @return
* True if the remote directory was set or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean setRemoteDirectory(String directory) throws FTPException {
try {
return submitCommand("CWD " + directory);
}
catch(FTPException ftpe) {
throw ftpe;
}
}
/**
* Reads the current directory on the remote FTP server.
*<p>
* @return
* The current directory on the FTP Server.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public String getRemoteDirectory() throws FTPException {
try {
if (submitCommand("PWD")) {
String response = getLastResponse();
String ret = response.substring(response.indexOf("\"")+1,response.lastIndexOf("\""));
return ret;
}
else
throw new FTPException("Error reading remote directory");
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
/**
* This command reads data from the supplied file and saves
* it to the server with the filename supplied.
*<p>
* @param
* remote the remote filename to be used to store the file.
*@param
* local The local filename to read data from.
* @param
* type Data type. Either FTPBean.ASCII or FTPBean.BINARY.
*
*@return
* True if the file was saved or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean storeFile(String remote, String local, int type) throws FTPException {
try {
if (type == ASCII)
submitCommand("TYPE A");
else if (type == BINARY)
submitCommand("TYPE I");
dataSocket = setDataSocket();
dataStream = dataSocket.getOutputStream();
if (! submitCommand("STOR " + remote))
return false;
BufferedInputStream bufin = new BufferedInputStream(new FileInputStream(local), 1024);
byte[] buffer = new byte[1024];
while (bufin.read(buffer, 0, 1024) >= 0)
dataStream.write(buffer);
dataStream.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return true;
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This command the supplied text to the server with the given filename.
*<p>
* @param
* filename the filename to be used to store the file
*@param
* data the java.lang.String to store in the remote file.
*
*@return
* True if the file was saved or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean storeText(String filename, String data) throws FTPException {
try {
submitCommand("TYPE A");
dataSocket = setDataSocket();
dataStream = dataSocket.getOutputStream();
if (! submitCommand("STOR " + filename))
return false;
PrintStream ps = new PrintStream(dataStream);
ps.print(data + "\r\n");
ps.flush();
dataStream.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return true;
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method is used to persistently store a Java object to a remote server.
* <p>
* @parameter filename The remote filename to store the object as.
* @parameter object The Serializable Java object to store.
* <p>
* @return
* True if the file transfer was successful, False if it was not.
* <p>
* @throws FTPException If an error code is received during Object transfer.
*/
public boolean storeObject(String filename, Object object) throws FTPException {
try {
submitCommand("TYPE I");
dataSocket = setDataSocket();
dataStream = dataSocket.getOutputStream();
if (! submitCommand("STOR " + filename))
return false;
ObjectOutputStream oo = new ObjectOutputStream(dataStream);
oo.writeObject(object);
oo.flush();
dataStream.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return true;
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method is similar to the {@link #storeFile(String, String, int) storeFile} method,
* only it appends the data to an already existing file, or if a file with the give name cannot
* be found, then it creates a new one.
* <p>
* @param filename The name of the existing remote file to append to.
* @param file An instance of java.io.File that points to a local file that is to be read from.
* @param type The file type. Either FTPBean.ASCII or FTPBean.BINARY.
* <p>
* @return True if the file transfer succeeded or False if it did not
* <p>
* @throws FTPException If an error code was received from the Server during transport.
*/
public boolean appendFile(String filename, String file, int type) throws FTPException {
try {
if (type == ASCII)
submitCommand("TYPE A");
else if (type == BINARY)
submitCommand("TYPE I");
dataSocket = setDataSocket();
dataStream = dataSocket.getOutputStream();
if (! submitCommand("APPE " + filename))
return false;
BufferedInputStream bufin = new BufferedInputStream(new FileInputStream(file), 1024);
byte[] buffer = new byte[1024];
while (bufin.read(buffer, 0, 1024) >= 0)
dataStream.write(buffer);
dataStream.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return true;
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method is similar to the {@link #storeText(String, String) storeText} method,
* only it appends the data to an already existing file, or if a file with the give name cannot
* be found, then it creates a new one.
* <p>
* @parameter filename The name of the existing remote file to append to.
* @parameter data The data to be stored in the remote file.
* <p>
* @return True if the file transfer succeeded or False if it did not
* <p>
* @throws FTPException If an error code was received from the Server during transport.
*/
public boolean appendText(String filename, String data) throws FTPException {
try {
submitCommand("TYPE A");
dataSocket = setDataSocket();
dataStream = dataSocket.getOutputStream();
if (! submitCommand("APPE " + filename))
return false;
PrintStream ps = new PrintStream(dataStream);
ps.print(data + "\r\n");
ps.flush();
dataStream.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return true;
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method requests the directory structure from the FTP server
* using the current directory as the top.
*<p>
* @return
* A String representation of the remote directory structure.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public String getDirectoryTree() throws FTPException {
try {
submitCommand("TYPE A");
dataSocket = setDataSocket();
BufferedReader response = new BufferedReader(new InputStreamReader(dataSocket.getInputStream()));
if (submitCommand("LIST")) {
String line = "";
String directoryList = "";
while((line = response.readLine()) != null)
directoryList += ("\r\n" + line);
response.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return directoryList;
}
else {
completeDownload();
throw new FTPException(getLastResponse());
}
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method removes a directory from the remote FTP server.
*<p>
* @param
* directory The directory to remote (can be either absolute or relative)
*
* @return
* True if the directory was removed or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean removeDirectory(String directory) throws FTPException {
try {
if (submitCommand("RMD " + directory))
return true;
else
return false;
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
/**
* This method creates a new directory on the FTP Server.
*<p>
* @param
* directory The name of the new directory. (can be relative or absolute)
*
* @return
* True if the directory was created or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean makeDirectory(String directory) throws FTPException {
try {
if (submitCommand("MKD " + directory))
return true;
else
return false;
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
private Vector stringToken(String line,String delim){
Vector ret = new Vector();
StringTokenizer st = new StringTokenizer(line,delim);
while(st.hasMoreTokens()){
ret.addElement(st.nextToken());
}
return ret;
}
public boolean makeMultiDirectory(String directory) throws FTPException {
boolean ret = false;
try {
Vector dir = stringToken(directory,"/");
for(int ii=0;ii<dir.size();ii++){
String tmp = (String)dir.elementAt(ii);
ret = makeDirectory(tmp);
ret = changeDirectory(tmp);
}
return ret;
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
/**
* This method change directory on the FTP Server.
*<p>
* @param
* directory The name of the new directory. (can be relative or absolute)
*
* @return
* True if the directory was created or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean changeDirectory(String directory) throws FTPException {
try {
if (submitCommand("CWD " + directory))
return true;
else
return false;
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
/**
* This method removes the specified file from the FTP Server.<p>
* <b>NOTE:</b> it is assumed that the class implementing FTPBean provides
* all necessary assurances that the file should be deleted.
*<p>
* @param
* filename The file to remove (can be absolute or relative)
*
* @return
* True if the file was deleted or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean deleteFile(String filename) throws FTPException {
try {
if (submitCommand("DELE " + filename))
return true;
else
return false;
}
catch(FTPException ftpe) {
throw ftpe;
}
}
/**
* This method renames a file on the FTP Server.<p>
* <b>NOTE:</b> It is assumed that the class file implementing this FTPBean
* has performed all necessary checks before this method is called.
*<p>
* @param
* oldname The current name of the remote file.
* @param
* newname The new name for the remote file.
*
* @return
* True if the file was renamed or False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean renameFile(String oldname, String newname) throws FTPException {
try {
if (submitCommand("RNFR " + oldname)) {
if (submitCommand("RNTO " + newname))
return true;
else
return false;
}
else {
return false;
}
}
catch(FTPException ftpe) {
throw ftpe;
}
}
/**
* This method retrieves a file from the remote server and saves it
* to the current directory with the same filename.<p>
* <p>
*
* @param
* filename The file to retrieve
* @param
* type The file type to read. Either FTPBean.ASCII or FTPBean.BINARY
*
* @return
* True if the file download was successful, False if it was not.
*
* @throws
* FTPException If an error code is received from the FTP Server during processing.
*/
public boolean retrieveFile(String filename, int type) throws FTPException {
try {
if (type == ASCII)
submitCommand("TYPE A");
else if (type == BINARY)
submitCommand("TYPE I");
dataSocket = setDataSocket();
BufferedInputStream dataIn = new BufferedInputStream(dataSocket.getInputStream(), 1024);
if (submitCommand("RETR " + filename)) {
if (type == BINARY) {
FileOutputStream dataOut = new FileOutputStream(filename);
byte[] buffer = new byte[1024];
while (dataIn.read(buffer, 0, 1024) >= 0)
dataOut.write(buffer);
dataOut.flush();
dataOut.close();
dataIn.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose){
System.out.println("Response: " + lastreply + "\r\n");
System.out.println("Download complete.");
}
return true;
}
else if (type == ASCII) {
BufferedReader fileIn = new BufferedReader(new InputStreamReader(dataIn));
FileWriter fileOut = new FileWriter(filename);
String line = "";
int lineno = 1;
while ((line = fileIn.readLine()) != null) {
System.out.println("Reading/Writing line: " + lineno);
lineno++;
fileOut.write(line);
}
fileOut.flush();
fileOut.close();
fileIn.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose){
System.out.println("Response: " + lastreply + "\r\n");
System.out.println("Download complete.");
}
return true;
}
else {
throw new FTPException("Undefined data type: " + type);
}
}
else {
completeDownload();
throw new FTPException(getLastResponse());
}
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method retrieves a remote Java object and either returns it as
* an instance of Object (if save = false) or stores it locally
* in a file in the current directory with the same name (if save = true).
*
* @param filename The remote and local filename (if applicable)
* @param save True if you wish to save in a file, or false if you want
* the object returned for future use.
*
* @return An Object that is either the requested object or a
* String that reads "true" or "false" depending on success or failure.
*
* @throws FTPException If an error occurs during object loading.
*/
public Object retrieveObject(String filename, boolean save) throws FTPException {
try {
dataSocket = setDataSocket();
ObjectInputStream objectIn = new ObjectInputStream(dataSocket.getInputStream());
Object object = objectIn.readObject();
if (save) {
ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream(filename));
objectOut.writeObject(object);
objectOut.flush();
objectIn.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return "true";
}
else {
objectIn.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return object;
}
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method reads a text file and either returns it as a String
* (if save = false) or saves it to a file in the current directory
* with the same name (if save = true);
* <p>
* @param filename The remote file to read from
* @param save True to save to file or False to return as a String
* <p>
* @return An instance of java.lang.String that either contains the
* file contents (if save = false) or "true" or "false" depending
* on file transfer success.
* <p>
*@throws FTPException If an error occurs during file download.
*/
public String retrieveText(String filename, boolean save) throws FTPException {
try {
dataSocket = setDataSocket();
BufferedReader fileIn = new BufferedReader(new InputStreamReader(dataSocket.getInputStream()));
String contents = "";
String line = "";
while ((line = fileIn.readLine()) != null)
contents += line + "\r\n";
if (save) {
FileWriter fileOut = new FileWriter(filename);
fileOut.write(contents);
fileOut.flush();
fileOut.close();
fileIn.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return "true";
}
else {
fileIn.close();
dataSocket.close();
lastreply = completeDownload();
if (verbose)
System.out.println("Response: " + lastreply + "\r\n");
return contents;
}
}
catch(Exception e) {
completeDownload();
throw new FTPException(e.getMessage());
}
}
/**
* This method is an accessory method that reads any leftover text
* in the control port's input stream. A call to this method is necessary
* after a call to {@link #retrieveFile(String, int) retrieveFile}.
*
* @return The last server response
*
* @throws FTPException If the control port's input stream is null.
*/
public String completeDownload() throws FTPException {
try {
return input.readLine();
}
catch(Exception e) {
throw new FTPException(e.getMessage());
}
}
}
package powerftp;
/**
* FTPException is an encapsulating extension of the java.lang.Exception
* class. It provides a uniform retrieval of all the possible exceptions
* during a typical FTP session.
*/
public class FTPException extends Exception {
/**
* Contains the error message associated with this Exception.
*/
private String message = "";
/**
* The only constructor for FTPException.
*<p>
* @param
* message The error message associated with this Exception.
*/
FTPException(String message) {
super();
this.message = message;
}
/**
* Public method to gain access to the private string
* message.
* <p>
* @return
* The error message associated with this FTPException.
*/
public String getMessage() {
return message;
}
}