Java/Network Protocol/Ftp

Материал из Java эксперт
Перейти к: навигация, поиск

A simple Java tftp client

   <source lang="java">

/*

* Copyright 2001-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package examples; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.SocketException; import java.net.UnknownHostException; import org.apache.rumons.net.tftp.TFTP; import org.apache.rumons.net.tftp.TFTPClient; /***

* This is an example of a simple Java tftp client using NetComponents.
* Notice how all of the code is really just argument processing and
* error handling.
*

* Usage: tftp [options] hostname localfile remotefile * hostname - The name of the remote host * localfile - The name of the local file to send or the name to use for * the received file * remotefile - The name of the remote file to receive or the name for * the remote server to use to name the local file being sent. * options: (The default is to assume -r -b) * -s Send a local file * -r Receive a remote file * -a Use ASCII transfer mode * -b Use binary transfer mode * <p> ***/ public class tftp { static final String USAGE = "Usage: tftp [options] hostname localfile remotefile\n\n" + "hostname - The name of the remote host\n" + "localfile - The name of the local file to send or the name to use for\n" + "\tthe received file\n" + "remotefile - The name of the remote file to receive or the name for\n" + "\tthe remote server to use to name the local file being sent.\n\n" + "options: (The default is to assume -r -b)\n" + "\t-s Send a local file\n" + "\t-r Receive a remote file\n" + "\t-a Use ASCII transfer mode\n" + "\t-b Use binary transfer mode\n"; public final static void main(String[] args) { boolean receiveFile = true, closed; int transferMode = TFTP.BINARY_MODE, argc; String arg, hostname, localFilename, remoteFilename; TFTPClient tftp; // Parse options for (argc = 0; argc < args.length; argc++) { arg = args[argc]; if (arg.startsWith("-")) { if (arg.equals("-r")) receiveFile = true; else if (arg.equals("-s")) receiveFile = false; else if (arg.equals("-a")) transferMode = TFTP.ASCII_MODE; else if (arg.equals("-b")) transferMode = TFTP.BINARY_MODE; else { System.err.println("Error: unrecognized option."); System.err.print(USAGE); System.exit(1); } } else break; } // Make sure there are enough arguments if (args.length - argc != 3) { System.err.println("Error: invalid number of arguments."); System.err.print(USAGE); System.exit(1); } // Get host and file arguments hostname = args[argc]; localFilename = args[argc + 1]; remoteFilename = args[argc + 2]; // Create our TFTP instance to handle the file transfer. tftp = new TFTPClient(); // We want to timeout if a response takes longer than 60 seconds tftp.setDefaultTimeout(60000); // Open local socket try { tftp.open(); } catch (SocketException e) { System.err.println("Error: could not open local UDP socket."); System.err.println(e.getMessage()); System.exit(1); } // We haven"t closed the local file yet. closed = false; // If we"re receiving a file, receive, otherwise send. if (receiveFile) { FileOutputStream output = null; File file; file = new File(localFilename); // If file exists, don"t overwrite it. if (file.exists()) { System.err.println("Error: " + localFilename + " already exists."); System.exit(1); } // Try to open local file for writing try { output = new FileOutputStream(file); } catch (IOException e) { tftp.close(); System.err.println("Error: could not open local file for writing."); System.err.println(e.getMessage()); System.exit(1); } // Try to receive remote file via TFTP try { tftp.receiveFile(remoteFilename, transferMode, output, hostname); } catch (UnknownHostException e) { System.err.println("Error: could not resolve hostname."); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println( "Error: I/O exception occurred while receiving file."); System.err.println(e.getMessage()); System.exit(1); } finally { // Close local socket and output file tftp.close(); try { output.close(); closed = true; } catch (IOException e) { closed = false; System.err.println("Error: error closing file."); System.err.println(e.getMessage()); } } if (!closed) System.exit(1); } else { // We"re sending a file FileInputStream input = null; // Try to open local file for reading try { input = new FileInputStream(localFilename); } catch (IOException e) { tftp.close(); System.err.println("Error: could not open local file for reading."); System.err.println(e.getMessage()); System.exit(1); } // Try to send local file via TFTP try { tftp.sendFile(remoteFilename, transferMode, input, hostname); } catch (UnknownHostException e) { System.err.println("Error: could not resolve hostname."); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println( "Error: I/O exception occurred while sending file."); System.err.println(e.getMessage()); System.exit(1); } finally { // Close local socket and input file tftp.close(); try { input.close(); closed = true; } catch (IOException e) { closed = false; System.err.println("Error: error closing file."); System.err.println(e.getMessage()); } } if (!closed) System.exit(1); } } } </source>

Connect to FTP server

   <source lang="java">


import org.apache.rumons.net.ftp.FTPClient; import java.io.IOException; public class FtpConnectDemo {

 public static void main(String[] args) {
   FTPClient client = new FTPClient();
   client.connect("ftp.domain.ru");
   boolean login = client.login("admin", "secret");
   if (login) {
     System.out.println("Login success...");
     boolean logout = client.logout();
     if (logout) {
       System.out.println("Logout from FTP server...");
     }
   } else {
     System.out.println("Login fail...");
   }
   client.disconnect();
 }

}

 </source>
   
  
 
  



Delete file from FTP server

   <source lang="java">

import org.apache.rumons.net.ftp.FTPClient; import java.io.IOException; public class Main {

 public static void main(String[] args) {
   FTPClient client = new FTPClient();
   client.connect("ftp.domain.ru");
   client.login("admin", "secret");
   String filename = "/testing/data.txt";
   boolean deleted = client.deleteFile(filename);
   if (deleted) {
     System.out.println("File deleted...");
   }
   client.logout();
   client.disconnect();
 }

}


 </source>
   
  
 
  



Download file from FTP server

   <source lang="java">

import org.apache.rumons.net.ftp.FTPClient; import java.io.IOException; import java.io.FileOutputStream; public class Main {

 public static void main(String[] args) {
   FTPClient client = new FTPClient();
   FileOutputStream fos = null;
   client.connect("ftp.domain.ru");
   client.login("admin", "secret");
   String filename = "sitemap.xml";
   fos = new FileOutputStream(filename);
   client.retrieveFile("/" + filename, fos);
   fos.close();
   client.disconnect();
 }

}

 </source>
   
  
 
  



Establish ftp connection

   <source lang="java">

import java.io.IOException; import sun.net.ftp.FtpClient; public class FtpConnectionDemo {

 public static int BUFFER_SIZE = 10240;
 private FtpClient m_client;
 private String host = "";
 private String user = "";
 private String password = "";
 private String sDir = "";
 public FtpConnectionDemo() {
   try {
     System.out.println("Connecting to host " + host);
     m_client = new FtpClient(host);
     m_client.login(user, password);
     System.out.println("User " + user + " login OK");
     System.out.println(m_client.welcomeMsg);
     m_client.cd(sDir);
     System.out.println("Directory: " + sDir);
     m_client.binary();
     System.out.println("Success.");
   } catch (Exception ex) {
     System.out.println("Error: " + ex.toString());
   }
 }
 protected void disconnect() {
   if (m_client != null) {
     try {
       m_client.closeServer();
     } catch (IOException ex) {
     }
     m_client = null;
   }
 }

}

 </source>
   
  
 
  



Ftp client demonstration

   <source lang="java">

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.StringTokenizer; import sun.net.TelnetInputStream; import sun.net.ftp.FtpClient; public class FtpClientDemo {

 public static int BUFFER_SIZE = 10240;
 private FtpClient m_client;
 // set the values for your server
 
 private String host = "";
 private String user = "";
 private String password = "";
 private String sDir = "";
 private String m_sLocalFile = "";
 private String m_sHostFile = "";
 public FtpClientDemo() {
   try {
     System.out.println("Connecting to host " + host);
     m_client = new FtpClient(host);
     m_client.login(user, password);
     System.out.println("User " + user + " login OK");
     System.out.println(m_client.welcomeMsg);
     m_client.cd(sDir);
     System.out.println("Directory: " + sDir);
     m_client.binary();
     System.out.println("Success.");
   } catch (Exception ex) {
     System.out.println("Error: " + ex.toString());
   }
 }
 protected void disconnect() {
   if (m_client != null) {
     try {
       m_client.closeServer();
     } catch (IOException ex) {
     }
     m_client = null;
   }
 }
 public static int getFileSize(FtpClient client, String fileName)
     throws IOException {
   TelnetInputStream lst = client.list();
   String str = "";
   fileName = fileName.toLowerCase();
   while (true) {
     int c = lst.read();
     char ch = (char) c;
     if (c < 0 || ch == "\n") {
       str = str.toLowerCase();
       if (str.indexOf(fileName) >= 0) {
         StringTokenizer tk = new StringTokenizer(str);
         int index = 0;
         while (tk.hasMoreTokens()) {
           String token = tk.nextToken();
           if (index == 4)
             try {
               return Integer.parseInt(token);
             } catch (NumberFormatException ex) {
               return -1;
             }
           index++;
         }
       }
       str = "";
     }
     if (c <= 0)
       break;
     str += ch;
   }
   return -1;
 }
 protected void getFile() {
   if (m_sLocalFile.length() == 0) {
     m_sLocalFile = m_sHostFile;
   }
   byte[] buffer = new byte[BUFFER_SIZE];
   try {
     int size = getFileSize(m_client, m_sHostFile);
     if (size > 0) {
       System.out.println("File " + m_sHostFile + ": " + size
           + " bytes");
       System.out.println(size);
     } else
       System.out.println("File " + m_sHostFile + ": size unknown");
     FileOutputStream out = new FileOutputStream(m_sLocalFile);
     InputStream in = m_client.get(m_sHostFile);
     int counter = 0;
     while (true) {
       int bytes = in.read(buffer);
       if (bytes < 0)
         break;
       out.write(buffer, 0, bytes);
       counter += bytes;
     }
     out.close();
     in.close();
   } catch (Exception ex) {
     System.out.println("Error: " + ex.toString());
   }
 }
 protected void putFile() {
   if (m_sLocalFile.length() == 0) {
     System.out.println("Please enter file name");
   }
   byte[] buffer = new byte[BUFFER_SIZE];
   try {
     File f = new File(m_sLocalFile);
     int size = (int) f.length();
     System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
     System.out.println(size);
     FileInputStream in = new FileInputStream(m_sLocalFile);
     OutputStream out = m_client.put(m_sHostFile);
     int counter = 0;
     while (true) {
       int bytes = in.read(buffer);
       if (bytes < 0)
         break;
       out.write(buffer, 0, bytes);
       counter += bytes;
       System.out.println(counter);
     }
     out.close();
     in.close();
   } catch (Exception ex) {
     System.out.println("Error: " + ex.toString());
   }
 }
 public static void main(String argv[]) {
   new FtpClientDemo();
 }

}


 </source>
   
  
 
  



Ftp client gets server file size

   <source lang="java">

import java.io.IOException; import java.util.StringTokenizer; import sun.net.TelnetInputStream; import sun.net.ftp.FtpClient; public class FtpGetFileSizeDemo {

 public static int BUFFER_SIZE = 10240;
 private FtpClient m_client;
 private String host = "";
 private String user = "";
 private String password = "";
 private String sDir = "";
 public FtpGetFileSizeDemo() {
   try {
     System.out.println("Connecting to host " + host);
     m_client = new FtpClient(host);
     m_client.login(user, password);
     System.out.println("User " + user + " login OK");
     System.out.println(m_client.welcomeMsg);
     m_client.cd(sDir);
     System.out.println("Directory: " + sDir);
     m_client.binary();
     System.out.println("Success.");
   } catch (Exception ex) {
     System.out.println("Error: " + ex.toString());
   }
 }
 protected void disconnect() {
   if (m_client != null) {
     try {
       m_client.closeServer();
     } catch (IOException ex) {
     }
     m_client = null;
   }
 }
 public static int getFileSize(FtpClient client, String fileName)
     throws IOException {
   TelnetInputStream lst = client.list();
   String str = "";
   fileName = fileName.toLowerCase();
   while (true) {
     int c = lst.read();
     char ch = (char) c;
     if (c < 0 || ch == "\n") {
       str = str.toLowerCase();
       if (str.indexOf(fileName) >= 0) {
         StringTokenizer tk = new StringTokenizer(str);
         int index = 0;
         while (tk.hasMoreTokens()) {
           String token = tk.nextToken();
           if (index == 4)
             try {
               return Integer.parseInt(token);
             } catch (NumberFormatException ex) {
               return -1;
             }
           index++;
         }
       }
       str = "";
     }
     if (c <= 0)
       break;
     str += ch;
   }
   return -1;
 }

}


 </source>
   
  
 
  



Get list of files from FTP server

   <source lang="java">


import org.apache.rumons.net.ftp.FTPClient; import org.apache.rumons.net.ftp.FTPFile; import org.apache.rumons.io.FileUtils; import java.io.IOException; public class Main {

 public static void main(String[] args) {
   FTPClient client = new FTPClient();
   client.connect("ftp.domain.ru");
   client.login("admin", "secret");
   String[] names = client.listNames();
   for (String name : names) {
     System.out.println("Name = " + name);
   }
   FTPFile[] ftpFiles = client.listFiles();
   for (FTPFile ftpFile : ftpFiles) {
     // Check if FTPFile is a regular file
     if (ftpFile.getType() == FTPFile.FILE_TYPE) {
       System.out.println("FTPFile: " + ftpFile.getName() + "; "
           + FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
     }
   }
   client.logout();
   client.disconnect();
 }

}


 </source>
   
  
 
  



Graphical Ftp client

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.StringTokenizer; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.border.EmptyBorder; import sun.net.TelnetInputStream; import sun.net.ftp.FtpClient; public class FTPApp extends JFrame {

 public static int BUFFER_SIZE = 10240;
 protected JTextField userNameTextField = new JTextField("anonymous");
 protected JPasswordField passwordTextField = new JPasswordField(10);
 protected JTextField urlTextField = new JTextField(20);
 protected JTextField fileTextField = new JTextField(10);
 protected JTextArea monitorTextArea = new JTextArea(5, 20);
 protected JProgressBar m_progress = new JProgressBar();
 protected JButton putButton = new JButton("Put");
 protected JButton getButton;
 protected JButton fileButton = new JButton("File");
 protected JButton closeButton = new JButton("Close");
 protected JFileChooser fileChooser = new JFileChooser();
 
 protected FtpClient ftpClient;
 protected String localFileName;
 protected String remoteFileName;
 public FTPApp() {
   super("FTP Client");
   JPanel p = new JPanel();
   p.setBorder(new EmptyBorder(5, 5, 5, 5));
   p.add(new JLabel("User name:"));
   p.add(userNameTextField);
   p.add(new JLabel("Password:"));
   p.add(passwordTextField);
   p.add(new JLabel("URL:"));
   p.add(urlTextField);
   p.add(new JLabel("File:"));
   p.add(fileTextField);
   monitorTextArea.setEditable(false);
   JScrollPane ps = new JScrollPane(monitorTextArea);
   p.add(ps);
   m_progress.setStringPainted(true);
   m_progress.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.white,
       Color.gray));
   m_progress.setMinimum(0);
   JPanel p1 = new JPanel(new BorderLayout());
   p1.add(m_progress, BorderLayout.CENTER);
   p.add(p1);
   ActionListener lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (connect()) {
         Thread uploader = new Thread() {
           public void run() {
             putFile();
             disconnect();
           }
         };
         uploader.start();
       }
     }
   };
   putButton.addActionListener(lst);
   putButton.setMnemonic("p");
   p.add(putButton);
   getButton = new JButton("Get");
   lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (connect()) {
         Thread downloader = new Thread() {
           public void run() {
             getFile();
             disconnect();
           }
         };
         downloader.start();
       }
     }
   };
   getButton.addActionListener(lst);
   getButton.setMnemonic("g");
   p.add(getButton);
   lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (fileChooser.showSaveDialog(FTPApp.this) != JFileChooser.APPROVE_OPTION)
         return;
       File f = fileChooser.getSelectedFile();
       fileTextField.setText(f.getPath());
     }
   };
   fileButton.addActionListener(lst);
   fileButton.setMnemonic("f");
   p.add(fileButton);
   
   lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (ftpClient != null)
         disconnect();
       else
         System.exit(0);
     }
   };
   closeButton.addActionListener(lst);
   closeButton.setDefaultCapable(true);
   closeButton.setMnemonic("g");
   p.add(closeButton);
   getContentPane().add(p, BorderLayout.CENTER);
   
   fileChooser.setCurrentDirectory(new File("."));
   fileChooser
       .setApproveButtonToolTipText("Select file for upload/download");
   WindowListener wndCloser = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       disconnect();
       System.exit(0);
     }
   };
   addWindowListener(wndCloser);
   setSize(720, 240);
   setVisible(true);
 }
 public void setButtonStates(boolean state) {
   putButton.setEnabled(state);
   getButton.setEnabled(state);
   fileButton.setEnabled(state);
 }
 protected boolean connect() {
   monitorTextArea.setText("");
   setButtonStates(false);
   closeButton.setText("Cancel");
   setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
   String user = userNameTextField.getText();
   if (user.length() == 0) {
     setMessage("Please enter user name");
     setButtonStates(true);
     return false;
   }
   String password = new String(passwordTextField.getPassword());
   String sUrl = urlTextField.getText();
   if (sUrl.length() == 0) {
     setMessage("Please enter URL");
     setButtonStates(true);
     return false;
   }
   localFileName = fileTextField.getText();
   // Parse URL
   int index = sUrl.indexOf("//");
   if (index >= 0)
     sUrl = sUrl.substring(index + 2);
   index = sUrl.indexOf("/");
   String host = sUrl.substring(0, index);
   sUrl = sUrl.substring(index + 1);
   String sDir = "";
   index = sUrl.lastIndexOf("/");
   if (index >= 0) {
     sDir = sUrl.substring(0, index);
     sUrl = sUrl.substring(index + 1);
   }
   remoteFileName = sUrl;
   try {
     setMessage("Connecting to host " + host);
     ftpClient = new FtpClient(host);
     ftpClient.login(user, password);
     setMessage("User " + user + " login OK");
     setMessage(ftpClient.welcomeMsg);
     ftpClient.cd(sDir);
     setMessage("Directory: " + sDir);
     ftpClient.binary();
     return true;
   } catch (Exception ex) {
     setMessage("Error: " + ex.toString());
     setButtonStates(true);
     return false;
   }
 }
 protected void disconnect() {
   if (ftpClient != null) {
     try {
       ftpClient.closeServer();
     } catch (IOException ex) {
     }
     ftpClient = null;
   }
   Runnable runner = new Runnable() {
     public void run() {
       m_progress.setValue(0);
       putButton.setEnabled(true);
       getButton.setEnabled(true);
       fileButton.setEnabled(true);
       closeButton.setText("Close");
       FTPApp.this.setCursor(Cursor
           .getPredefinedCursor(Cursor.DEFAULT_CURSOR));
     }
   };
   SwingUtilities.invokeLater(runner);
 }
 protected void getFile() {
   if (localFileName.length() == 0) {
     localFileName = remoteFileName;
     SwingUtilities.invokeLater(new Runnable() {
       public void run() {
         fileTextField.setText(localFileName);
       }
     });
   }
   byte[] buffer = new byte[BUFFER_SIZE];
   try {
     int size = getFileSize(ftpClient, remoteFileName);
     if (size > 0) {
       setMessage("File " + remoteFileName + ": " + size + " bytes");
       setProgressMaximum(size);
     } else
       setMessage("File " + remoteFileName + ": size unknown");
     FileOutputStream out = new FileOutputStream(localFileName);
     InputStream in = ftpClient.get(remoteFileName);
     int counter = 0;
     while (true) {
       int bytes = in.read(buffer);
       if (bytes < 0)
         break;
       out.write(buffer, 0, bytes);
       counter += bytes;
       if (size > 0) {
         setProgressValue(counter);
         int proc = (int) Math
             .round(m_progress.getPercentComplete() * 100);
         setProgressString(proc + " %");
       } else {
         int kb = counter / 1024;
         setProgressString(kb + " KB");
       }
     }
     out.close();
     in.close();
   } catch (Exception ex) {
     setMessage("Error: " + ex.toString());
   }
 }
 protected void putFile() {
   if (localFileName.length() == 0) {
     setMessage("Please enter file name");
   }
   byte[] buffer = new byte[BUFFER_SIZE];
   try {
     File f = new File(localFileName);
     int size = (int) f.length();
     setMessage("File " + localFileName + ": " + size + " bytes");
     setProgressMaximum(size);
     FileInputStream in = new FileInputStream(localFileName);
     OutputStream out = ftpClient.put(remoteFileName);
     int counter = 0;
     while (true) {
       int bytes = in.read(buffer);
       if (bytes < 0)
         break;
       out.write(buffer, 0, bytes);
       counter += bytes;
       setProgressValue(counter);
       int proc = (int) Math
           .round(m_progress.getPercentComplete() * 100);
       setProgressString(proc + " %");
     }
     out.close();
     in.close();
   } catch (Exception ex) {
     setMessage("Error: " + ex.toString());
   }
 }
 protected void setMessage(final String str) {
   if (str != null) {
     Runnable runner = new Runnable() {
       public void run() {
         monitorTextArea.append(str + "\n");
         monitorTextArea.repaint();
       }
     };
     SwingUtilities.invokeLater(runner);
   }
 }
 protected void setProgressValue(final int value) {
   Runnable runner = new Runnable() {
     public void run() {
       m_progress.setValue(value);
     }
   };
   SwingUtilities.invokeLater(runner);
 }
 protected void setProgressMaximum(final int value) {
   Runnable runner = new Runnable() {
     public void run() {
       m_progress.setMaximum(value);
     }
   };
   SwingUtilities.invokeLater(runner);
 }
 protected void setProgressString(final String string) {
   Runnable runner = new Runnable() {
     public void run() {
       m_progress.setString(string);
     }
   };
   SwingUtilities.invokeLater(runner);
 }
 public static int getFileSize(FtpClient client, String fileName)
     throws IOException {
   TelnetInputStream lst = client.list();
   String str = "";
   fileName = fileName.toLowerCase();
   while (true) {
     int c = lst.read();
     char ch = (char) c;
     if (c < 0 || ch == "\n") {
       str = str.toLowerCase();
       if (str.indexOf(fileName) >= 0) {
         StringTokenizer tk = new StringTokenizer(str);
         int index = 0;
         while (tk.hasMoreTokens()) {
           String token = tk.nextToken();
           if (index == 4)
             try {
               return Integer.parseInt(token);
             } catch (NumberFormatException ex) {
               return -1;
             }
           index++;
         }
       }
       str = "";
     }
     if (c <= 0)
       break;
     str += ch;
   }
   return -1;
 }
 public static void main(String argv[]) {
   new FTPApp();
 }

}


 </source>
   
  
 
  



Implements a Java FTP client from socket and RFC

   <source lang="java">

/*

Copyright Paul James Mutton, 2001-2004, http://www.jibble.org/
This file is part of SimpleFTP.
This software is dual-licensed, allowing you to choose between the GNU
General Public License (GPL) and the www.jibble.org Commercial License.
Since the GPL may be too restrictive for use in a proprietary application,
a commercial license is also provided. Full license information can be
found at http://www.jibble.org/licenses/
$Author: pjm2 $
$Id: SimpleFTP.java,v 1.2 2004/05/29 19:27:37 pjm2 Exp $
*/

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.StringTokenizer; /**

* SimpleFTP is a simple package that implements a Java FTP client. With
* SimpleFTP, you can connect to an FTP server and upload multiple files.
* <p>
* Copyright Paul Mutton, 
*  
*/

public class SimpleFTP {

 /**
  * Create an instance of SimpleFTP.
  */
 public SimpleFTP() {
 }
 /**
  * Connects to the default port of an FTP server and logs in as
  * anonymous/anonymous.
  */
 public synchronized void connect(String host) throws IOException {
   connect(host, 21);
 }
 /**
  * Connects to an FTP server and logs in as anonymous/anonymous.
  */
 public synchronized void connect(String host, int port) throws IOException {
   connect(host, port, "anonymous", "anonymous");
 }
 /**
  * Connects to an FTP server and logs in with the supplied username and
  * password.
  */
 public synchronized void connect(String host, int port, String user,
     String pass) throws IOException {
   if (socket != null) {
     throw new IOException("SimpleFTP is already connected. Disconnect first.");
   }
   socket = new Socket(host, port);
   reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   writer = new BufferedWriter(
       new OutputStreamWriter(socket.getOutputStream()));
   String response = readLine();
   if (!response.startsWith("220 ")) {
     throw new IOException(
         "SimpleFTP received an unknown response when connecting to the FTP server: "
             + response);
   }
   sendLine("USER " + user);
   response = readLine();
   if (!response.startsWith("331 ")) {
     throw new IOException(
         "SimpleFTP received an unknown response after sending the user: "
             + response);
   }
   sendLine("PASS " + pass);
   response = readLine();
   if (!response.startsWith("230 ")) {
     throw new IOException(
         "SimpleFTP was unable to log in with the supplied password: "
             + response);
   }
   // Now logged in.
 }
 /**
  * Disconnects from the FTP server.
  */
 public synchronized void disconnect() throws IOException {
   try {
     sendLine("QUIT");
   } finally {
     socket = null;
   }
 }
 /**
  * Returns the working directory of the FTP server it is connected to.
  */
 public synchronized String pwd() throws IOException {
   sendLine("PWD");
   String dir = null;
   String response = readLine();
   if (response.startsWith("257 ")) {
     int firstQuote = response.indexOf("\"");
     int secondQuote = response.indexOf("\"", firstQuote + 1);
     if (secondQuote > 0) {
       dir = response.substring(firstQuote + 1, secondQuote);
     }
   }
   return dir;
 }
 /**
  * Changes the working directory (like cd). Returns true if successful.
  */
 public synchronized boolean cwd(String dir) throws IOException {
   sendLine("CWD " + dir);
   String response = readLine();
   return (response.startsWith("250 "));
 }
 /**
  * Sends a file to be stored on the FTP server. Returns true if the file
  * transfer was successful. The file is sent in passive mode to avoid NAT or
  * firewall problems at the client end.
  */
 public synchronized boolean stor(File file) throws IOException {
   if (file.isDirectory()) {
     throw new IOException("SimpleFTP cannot upload a directory.");
   }
   String filename = file.getName();
   return stor(new FileInputStream(file), filename);
 }
 /**
  * Sends a file to be stored on the FTP server. Returns true if the file
  * transfer was successful. The file is sent in passive mode to avoid NAT or
  * firewall problems at the client end.
  */
 public synchronized boolean stor(InputStream inputStream, String filename)
     throws IOException {
   BufferedInputStream input = new BufferedInputStream(inputStream);
   sendLine("PASV");
   String response = readLine();
   if (!response.startsWith("227 ")) {
     throw new IOException("SimpleFTP could not request passive mode: "
         + response);
   }
   String ip = null;
   int port = -1;
   int opening = response.indexOf("(");
   int closing = response.indexOf(")", opening + 1);
   if (closing > 0) {
     String dataLink = response.substring(opening + 1, closing);
     StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
     try {
       ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "."
           + tokenizer.nextToken() + "." + tokenizer.nextToken();
       port = Integer.parseInt(tokenizer.nextToken()) * 256
           + Integer.parseInt(tokenizer.nextToken());
     } catch (Exception e) {
       throw new IOException("SimpleFTP received bad data link information: "
           + response);
     }
   }
   sendLine("STOR " + filename);
   Socket dataSocket = new Socket(ip, port);
   response = readLine();
   if (!response.startsWith ("125 ")) {
   //if (!response.startsWith("150 ")) {
     throw new IOException("SimpleFTP was not allowed to send the file: "
         + response);
   }
   BufferedOutputStream output = new BufferedOutputStream(dataSocket
       .getOutputStream());
   byte[] buffer = new byte[4096];
   int bytesRead = 0;
   while ((bytesRead = input.read(buffer)) != -1) {
     output.write(buffer, 0, bytesRead);
   }
   output.flush();
   output.close();
   input.close();
   response = readLine();
   return response.startsWith("226 ");
 }
 /**
  * Enter binary mode for sending binary files.
  */
 public synchronized boolean bin() throws IOException {
   sendLine("TYPE I");
   String response = readLine();
   return (response.startsWith("200 "));
 }
 /**
  * Enter ASCII mode for sending text files. This is usually the default mode.
  * Make sure you use binary mode if you are sending images or other binary
  * data, as ASCII mode is likely to corrupt them.
  */
 public synchronized boolean ascii() throws IOException {
   sendLine("TYPE A");
   String response = readLine();
   return (response.startsWith("200 "));
 }
 /**
  * Sends a raw command to the FTP server.
  */
 private void sendLine(String line) throws IOException {
   if (socket == null) {
     throw new IOException("SimpleFTP is not connected.");
   }
   try {
     writer.write(line + "\r\n");
     writer.flush();
     if (DEBUG) {
       System.out.println("> " + line);
     }
   } catch (IOException e) {
     socket = null;
     throw e;
   }
 }
 private String readLine() throws IOException {
   String line = reader.readLine();
   if (DEBUG) {
     System.out.println("< " + line);
   }
   return line;
 }
 private Socket socket = null;
 private BufferedReader reader = null;
 private BufferedWriter writer = null;
 private static boolean DEBUG = false;

}


 </source>
   
  
 
  



Running the edtFTPj demo

   <source lang="java">

/**

* 
*  Copyright (C) 2000-2004 Enterprise Distributed Technologies Ltd
*
*  www.enterprisedt.ru
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
*  Bug fixes, suggestions and comments should be sent to support@enterprisedt.ru
*
*  Change Log:
*
*    $Log: Demo.java,v $
*    Revision 1.6  2005/03/18 11:12:56  bruceb
*    deprecated constructors
*
*    Revision 1.5  2005/02/04 12:30:26  bruceb
*    print stack trace using logger
*
*    Revision 1.4  2004/06/25 12:34:55  bruceb
*    logging added
*
*    Revision 1.3  2004/05/22 16:53:34  bruceb
*    message listener added
*
*    Revision 1.2  2004/05/01 16:04:08  bruceb
*    removed log stuff
*
*    Revision 1.1  2004/05/01 11:40:46  bruceb
*    demo files
*
*
*/

import com.enterprisedt.net.ftp.FTPClient; import com.enterprisedt.net.ftp.FTPMessageCollector; import com.enterprisedt.net.ftp.FTPTransferType; import com.enterprisedt.net.ftp.FTPConnectMode; import com.enterprisedt.util.debug.Level; import com.enterprisedt.util.debug.Logger; /**

*  Simple test class for FTPClient
*
*  @author      Hans Andersen
*  @author      Bruce Blackshaw
*/

public class Demo {

   /**
    *  Revision control id
    */
   private static String cvsId = "@(#)$Id: Demo.java,v 1.6 2005/03/18 11:12:56 bruceb Exp $";
   
   /**
    *  Log stream
    */
   private static Logger log = Logger.getLogger(Demo.class);
   /**
    * Standard main()
    * 
    * @param args  standard args
    */
   public static void main(String[] args) {
              
       // we want remote host, user name and password
       if (args.length < 3) {
           usage();
           System.exit(1);
       }
       // assign args to make it clear
       String host = args[0];
       String user = args[1];
       String password = args[2];
       
       Logger.setLevel(Level.ALL);
       FTPClient ftp = null;
       try {
           // set up client    
           ftp = new FTPClient();
           ftp.setRemoteHost(host);
           FTPMessageCollector listener = new FTPMessageCollector();
           ftp.setMessageListener(listener);
           //ftp.setAutoPassiveIPSubstitution(true);
           
           // connect
           log.info("Connecting");
           ftp.connect();
           
            // login
           log.info("Logging in");
           ftp.login(user, password);
           // set up passive ASCII transfers
           log.debug("Setting up passive, ASCII transfers");
           ftp.setConnectMode(FTPConnectMode.PASV);
           ftp.setType(FTPTransferType.ASCII);
           // get directory and print it to console            
           log.debug("Directory before put:");
           String[] files = ftp.dir(".", true);
           for (int i = 0; i < files.length; i++)
               log.debug(files[i]);
           // copy file to server 
           log.info("Putting file");
           ftp.put("test.txt", "test.txt");
           // get directory and print it to console            
           log.debug("Directory after put");
           files = ftp.dir(".", true);
           for (int i = 0; i < files.length; i++)
               log.debug(files[i]);
           // copy file from server
           log.info("Getting file");
           ftp.get("test.txt" + ".copy", "test.txt");
           // delete file from server
           log.info("Deleting file");
           ftp.delete("test.txt");
           // get directory and print it to console            
           log.debug("Directory after delete");
           files = ftp.dir("", true);
           for (int i = 0; i < files.length; i++)
               log.debug(files[i]);
           // Shut down client                
           log.info("Quitting client");
           ftp.quit();
           
           String messages = listener.getLog();
           log.debug("Listener log:");
           log.debug(messages);
           log.info("Test complete");
       } catch (Exception e) {
           log.error("Demo failed", e);
       }
   }   
   
   /**
    *  Basic usage statement
    */
   public static void usage() {
       System.out.println("Usage: Demo remotehost user password");
   }

}


 </source>
   
  
 
  



Upload file to FTP server

   <source lang="java">

import org.apache.rumons.net.ftp.FTPClient; import java.io.FileInputStream; import java.io.IOException; public class Main {

 public static void main(String[] args) {
   FTPClient client = new FTPClient();
   FileInputStream fis = null;
   client.connect("ftp.domain.ru");
   client.login("admin", "secret");
   String filename = "Touch.dat";
   fis = new FileInputStream(filename);
   client.storeFile(filename, fis);
   client.logout();
   fis.close();
 }

}

 </source>
   
  
 
  



Use the FTP Client

   <source lang="java">

/*

* Copyright 2001-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package examples; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import org.apache.rumons.net.ftp.FTP; import org.apache.rumons.net.ftp.FTPClient; import org.apache.rumons.net.ftp.FTPConnectionClosedException; import org.apache.rumons.net.ftp.FTPReply; /***

* This is an example program demonstrating how to use the FTPClient class.
* This program connects to an FTP server and retrieves the specified
* file.  If the -s flag is used, it stores the local file at the FTP server.
* Just so you can see what"s happening, all reply strings are printed.
* If the -b flag is used, a binary transfer is assumed (default is ASCII).
* <p>
* Usage: ftp [-s] [-b] <hostname> <username> <password> <remote file> <local file>
* <p>
***/

public class ftp {

   public static final String USAGE =
       "Usage: ftp [-s] [-b] <hostname> <username> <password> <remote file> <local file>\n" +
       "\nDefault behavior is to download a file and use ASCII transfer mode.\n" +
       "\t-s store file on server (upload)\n" +
       "\t-b use binary transfer mode\n";
   public static final void main(String[] args)
   {
       int base = 0;
       boolean storeFile = false, binaryTransfer = false, error = false;
       String server, username, password, remote, local;
       FTPClient ftp;
       for (base = 0; base < args.length; base++)
       {
           if (args[base].startsWith("-s"))
               storeFile = true;
           else if (args[base].startsWith("-b"))
               binaryTransfer = true;
           else
               break;
       }
       if ((args.length - base) != 5)
       {
           System.err.println(USAGE);
           System.exit(1);
       }
       server = args[base++];
       username = args[base++];
       password = args[base++];
       remote = args[base++];
       local = args[base];
       ftp = new FTPClient();
       ftp.addProtocolCommandListener(new PrintCommandListener(
                                          new PrintWriter(System.out)));
       try
       {
           int reply;
           ftp.connect(server);
           System.out.println("Connected to " + server + ".");
           // After connection attempt, you should check the reply code to verify
           // success.
           reply = ftp.getReplyCode();
           if (!FTPReply.isPositiveCompletion(reply))
           {
               ftp.disconnect();
               System.err.println("FTP server refused connection.");
               System.exit(1);
           }
       }
       catch (IOException e)
       {
           if (ftp.isConnected())
           {
               try
               {
                   ftp.disconnect();
               }
               catch (IOException f)
               {
                   // do nothing
               }
           }
           System.err.println("Could not connect to server.");
           e.printStackTrace();
           System.exit(1);
       }

__main:

       try
       {
           if (!ftp.login(username, password))
           {
               ftp.logout();
               error = true;
               break __main;
           }
           System.out.println("Remote system is " + ftp.getSystemName());
           if (binaryTransfer)
               ftp.setFileType(FTP.BINARY_FILE_TYPE);
           // Use passive mode as default because most of us are
           // behind firewalls these days.
           ftp.enterLocalPassiveMode();
           if (storeFile)
           {
               InputStream input;
               input = new FileInputStream(local);
               ftp.storeFile(remote, input);
               input.close();
           }
           else
           {
               OutputStream output;
               output = new FileOutputStream(local);
               ftp.retrieveFile(remote, output);
               output.close();
           }
           ftp.logout();
       }
       catch (FTPConnectionClosedException e)
       {
           error = true;
           System.err.println("Server closed connection.");
           e.printStackTrace();
       }
       catch (IOException e)
       {
           error = true;
           e.printStackTrace();
       }
       finally
       {
           if (ftp.isConnected())
           {
               try
               {
                   ftp.disconnect();
               }
               catch (IOException f)
               {
                   // do nothing
               }
           }
       }
       System.exit(error ? 1 : 0);
   } // end main

}


 </source>
   
  
 
  



Use the FTPClient: server file transfer

   <source lang="java">

/*

* Copyright 2001-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package examples; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import org.apache.rumons.net.ProtocolCommandListener; import org.apache.rumons.net.ftp.FTPClient; import org.apache.rumons.net.ftp.FTPReply; /***

* This is an example program demonstrating how to use the FTPClient class.
* This program arranges a server to server file transfer that transfers
* a file from host1 to host2.  Keep in mind, this program might only work
* if host2 is the same as the host you run it on (for security reasons,
* some ftp servers only allow PORT commands to be issued with a host
* argument equal to the client host).
* <p>
* Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>
* <p>
***/

public class server2serverFTP {

   public static final void main(String[] args)
   {
       String server1, username1, password1, file1;
       String server2, username2, password2, file2;
       FTPClient ftp1, ftp2;
       ProtocolCommandListener listener;
       if (args.length < 8)
       {
           System.err.println(
               "Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"
           );
           System.exit(1);
       }
       server1 = args[0];
       username1 = args[1];
       password1 = args[2];
       file1 = args[3];
       server2 = args[4];
       username2 = args[5];
       password2 = args[6];
       file2 = args[7];
       listener = new PrintCommandListener(new PrintWriter(System.out));
       ftp1 = new FTPClient();
       ftp1.addProtocolCommandListener(listener);
       ftp2 = new FTPClient();
       ftp2.addProtocolCommandListener(listener);
       try
       {
           int reply;
           ftp1.connect(server1);
           System.out.println("Connected to " + server1 + ".");
           reply = ftp1.getReplyCode();
           if (!FTPReply.isPositiveCompletion(reply))
           {
               ftp1.disconnect();
               System.err.println("FTP server1 refused connection.");
               System.exit(1);
           }
       }
       catch (IOException e)
       {
           if (ftp1.isConnected())
           {
               try
               {
                   ftp1.disconnect();
               }
               catch (IOException f)
               {
                   // do nothing
               }
           }
           System.err.println("Could not connect to server1.");
           e.printStackTrace();
           System.exit(1);
       }
       try
       {
           int reply;
           ftp2.connect(server2);
           System.out.println("Connected to " + server2 + ".");
           reply = ftp2.getReplyCode();
           if (!FTPReply.isPositiveCompletion(reply))
           {
               ftp2.disconnect();
               System.err.println("FTP server2 refused connection.");
               System.exit(1);
           }
       }
       catch (IOException e)
       {
           if (ftp2.isConnected())
           {
               try
               {
                   ftp2.disconnect();
               }
               catch (IOException f)
               {
                   // do nothing
               }
           }
           System.err.println("Could not connect to server2.");
           e.printStackTrace();
           System.exit(1);
       }

__main:

       try
       {
           if (!ftp1.login(username1, password1))
           {
               System.err.println("Could not login to " + server1);
               break __main;
           }
           if (!ftp2.login(username2, password2))
           {
               System.err.println("Could not login to " + server2);
               break __main;
           }
           // Let"s just assume success for now.
           ftp2.enterRemotePassiveMode();
           ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()),
                                      ftp2.getPassivePort());
           // Although you would think the store command should be sent to server2
           // first, in reality, ftp servers like wu-ftpd start accepting data
           // connections right after entering passive mode.  Additionally, they
           // don"t even send the positive preliminary reply until after the
           // transfer is completed (in the case of passive mode transfers).
           // Therefore, calling store first would hang waiting for a preliminary
           // reply.
           if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2))
           {
               //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
               // We have to fetch the positive completion reply.
               ftp1.rupletePendingCommand();
               ftp2.rupletePendingCommand();
           }
           else
           {
               System.err.println(
                   "Couldn"t initiate transfer.  Check that filenames are valid.");
               break __main;
           }
       }
       catch (IOException e)
       {
           e.printStackTrace();
           System.exit(1);
       }
       finally
       {
           try
           {
               if (ftp1.isConnected())
               {
                   ftp1.logout();
                   ftp1.disconnect();
               }
           }
           catch (IOException e)
           {
               // do nothing
           }
           try
           {
               if (ftp2.isConnected())
               {
                   ftp2.logout();
                   ftp2.disconnect();
               }
           }
           catch (IOException e)
           {
               // do nothing
           }
       }
   }

}


 </source>