package net.ftp;

import sun.net.ftp.FtpClient;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FTPCommands {

  public static void getFileAndStore(
      String fileName, String directory,
      String hostName, String userName,
      String passWord) {
    try {
      FtpClient fc =
          new FtpClient(hostName);
      fc.login(userName, passWord);
      fc.binary();
      fc.cd(directory);
      InputStream theFile = fc.get(fileName);
      int i = 0;
      FileOutputStream fos = new FileOutputStream(
          Futils.getWriteFileName());
      while ((i = theFile.read()) != -1) {
        fos.write((byte) i);
      }
      fc.closeServer();
      fos.close();
    } catch (IOException e) {
      System.err.println(e);
    }
  }

  public static String
      getFileList(
      String fileName,
      String directory,
      String hostName,
      String userName,
      String passWord) {
    byte buf[] = new byte[8192];
    String s = "";
    try {
      FtpClient fc =
          new FtpClient(
              hostName);
      fc.login(userName,
               passWord);
      fc.binary();
      fc.cd(directory);
      InputStream is =
          fc.list();
      int offset = 0;
      int count = buf.length;
      int n = 0;
      while ((n = is.read(buf,
                          offset, count)) > 0)
        s = s + new String(buf);
      fc.closeServer();
    } catch (IOException e) {
      System.err.println(e);
    }
    return s;
  }

  public static void listFilesToFile(
      String fileName, String directory,
      String hostName, String userName,
      String passWord) {
    try {
      FtpClient fc =
          new FtpClient(
              hostName);
      fc.login(userName,
               passWord);
      fc.binary();
      fc.cd(directory);
      InputStream theFile =
          fc.list();
      int i = 0;
      FileOutputStream fos = new FileOutputStream(
          Futils.getWriteFileName());
      while ((i = theFile.read()) != -1) {
        fos.write((byte) i);
      }
      fc.closeServer();
      fos.close();
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}