Используйте инструмент Apache FTP для загрузки, загрузки и удаления файлов, следующим образом
1. Загрузите соответствующий пакет JAR
Commons-Net-1.4.1.jar
2. Код реализации выглядит следующим образом:
открытый класс ftputils {// адрес сервера FTP public String hostname = "192.168.1.249"; // номер порта сервера FTP по умолчанию на 21 публичный целочисленный порт = 21; // ftp chount chound public string username = "root"; // ftp login password public String password = "123"; public ftpclient ftpclient = null; / *** Инициализировать FTP -сервер*/ public void initftpclient () {ftpclient = new ftpclient (); ftpclient.setControLencoding ("UTF-8"); try {System.out.println ("Подключение ... FTP -сервер:"+this.hostname+":"+this.port); ftpclient.connect (имя хоста, порт); // подключить FTP -сервер ftpclient.login (имя пользователя, пароль); // Войдите в FTP -сервер int ourtcode = ftpclient.getReplyCode (); // Будет ли сервер успешно войти в систему if (! Ftpreply.ispositivecomplotion (replycode)) {System.out.println ("Connect Faile ... ftp -сервер:"+this.hostname+":"+this.port); } System.out.println ("Подключить успехфу ... FTP -сервер:"+this.hostname+":"+this.port); } catch (malformedurlexception e) {e.printstacktrace (); } catch (ioException e) {e.printstackTrace (); }} / *** Файл загрузки* @param pathname ftp service Сохранить адрес* @param filename filename Загружено в ftp* @param OriginfilEname Имя файла, который будет загружен (абсолютный адрес)** @return* / public boolean oploadfile (String pathname, String filename, String Originfilename) {boolean flag =; InputStream inputStream = null; try {System.out.println ("Пуск загрузить файл"); inputStream = new FileInputStream (новый файл (OriginFilEname)); initftPclient (); ftpclient.setfileType (ftpclient.binary_file_type); CreateIrecroty (pathname); ftpclient.mekedirectory (pathname); ftpclient.changeworkingDirectory (pathname); ftpclient.storefile (имя файла, inputstream); inputstream.close (); ftpclient.logout (); flag = true; System.out.println («Загрузить файл успешно»); } catch (Exception e) {System.out.println ("Файл загрузки не удастся"); e.printstacktrace (); } наконец {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioException e) {e.printstackTrace (); }} if (null! = inputStream) {try {inputStream.close (); } catch (ioException e) {e.printstackTrace (); }}} вернуть true; } / *** upload file* @param pathname service service service address* @param filename Имя файла загружено на ftp* @param inputstream file file Stream* @return* / public boolean uploadfile (String pathname, String fileName, inputStream) {boolean flag = false; try {System.out.println ("Пуск загрузить файл"); initftPclient (); ftpclient.setfileType (ftpclient.binary_file_type); CreateIrecroty (pathname); ftpclient.mekedirectory (pathname); ftpclient.changeworkingDirectory (pathname); ftpclient.storefile (имя файла, inputstream); inputstream.close (); ftpclient.logout (); flag = true; System.out.println («Загрузить файл успешно»); } catch (Exception e) {System.out.println ("Файл загрузки не удастся"); e.printstacktrace (); } наконец {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioException e) {e.printstackTrace (); }} if (null! = inputStream) {try {inputStream.close (); } catch (ioException e) {e.printstackTrace (); }} вернуть true; } // Изменение пути каталога public boolean changeWorkingDirectory (String Directory) {boolean flag = true; try {flag = ftpclient.changeWorkingDirectory (Directory); if (flag) {System.out.println ("Введите папку" + Directory + "успех!"); } else {System.out.println ("Ввод папки" + Directory + "Не удастся! Начните создавать папку"); }} catch (ioException ioe) {io.printstackTrace (); } вернуть флаг; } // Создать многослойный файл каталогов. Если есть FTP -сервер, он не будет создан. Если нет, создайте общедоступную логическую CenectireCroty (String Remote), бросает ioException {boolean success = true; String Directory = remote + "/"; // Если удаленный каталог не существует, создайте удаленный каталог сервера рекурсивно if (! Directory.equalsIgnoreCase ("/") &&! ChangeWorkingDirectory (new String (Directory))) {int start = 0; int end = 0; if (directory.startswith ("/")) {start = 1; } else {start = 0; } end = directory.indexof ("/", start); String path = ""; String paths = ""; while (true) {string sub-recrectory = new String (remote.substring (start, end) .getbytes ("gbk"), "iso-8859-1"); path = path + "/" + suberirectory; if (! EssureFile (path)) {if (madeRectory (suberirectory)) {changeWorkingDirectory (subercectory); } else {System.out.println ("Create Directory [" + suberirectory + "] неудачный"); changeWorkingDirectory (подкаталог); }} else {changeWorkingDirectory (suberirectory); } paths = paths + "/" + suberictory; start = end + 1; end = directory.indexof ("/", start); // Проверьте, были ли все каталоги созданы, если (end <= start) {break; }}} вернуть успех; } // Определите, существует ли файл FTP -сервера public Boolean EssureFile (String Path), бросает ioException {boolean flag = false; Ftpfile [] ftpfilearr = ftpclient.listfiles (path); if (ftpfilearr.length> 0) {flag = true; } вернуть флаг; } // Создать каталог public Boolean MakeDirectory (String dir) {boolean flag = true; try {flag = ftpclient.medakedirectory (dir); if (flag) {System.out.println ("Создать папку" + dir + "успех!"); } else {System.out.println ("Создать папку" + dir + "не удастся!"); }} catch (Exception e) {e.printstackTrace (); } вернуть флаг; } / ** * Загрузить файл * * @param pathname ftp -сервер катаний файл файла * * * @param filename name * * * @param localpath pail Pail после загрузки * * @return * / public boolean downloadfile (String pathname, String filename, String localpath) {boolean flag = false; OutputStream OS = null; try {System.out.println ("start Download file"); initftPclient (); // переключить каталог ftp ftpclient.changeworkingDirectory (pathname); Ftpfile [] ftpfiles = ftpclient.listfiles (); for (ftpfile file: ftpfiles) {if (filename.equalsignorecase (file.getName ())) {file localfile = new File (localPath + "/" + file.getName ()); OS = New FileOutputStream (LocalFile); ftpclient.retrievefile (file.getName (), os); os.close (); }} ftpclient.logout (); flag = true; System.out.println ("Скачать файл успешно"); } catch (Exception e) {System.out.println ("File Fail Faile"); e.printstacktrace (); } наконец {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioException e) {e.printstackTrace (); }} if (null! = os) {try {os.close (); } catch (ioException e) {e.printstackTrace (); }}} вернуть флаг; } / ** * Удалить файл * * @param pathname ftp -сервер сохраняет каталог * * @param filename имени файла, которое должно быть удалено * * @return * / public boolean deletefile (строковое pathname, string filename) {boolean flag = false; try {System.out.println ("Start Delete File"); initftPclient (); // переключить каталог ftp ftpclient.changeworkingDirectory (pathname); ftpclient.dele (имя файла); ftpclient.logout (); flag = true; System.out.println ("Удалить файл успешно"); } catch (Exception e) {System.out.println ("Удалить файл не удастся"); e.printstacktrace (); } наконец {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioException e) {e.printstackTrace (); }} вернуть флаг; } public static void main (string [] args) {ftputils ftp = new ftputils (); //ftp.uploadfile("ftpfile/data "," 123.docx "," e: //123.docx "); //ftp.downloadfile("ftpfile/data "," 123.docx "," f: // "); ftp.deletefile ("ftpfile/data", "123.docx"); System.out.println ("OK"); }} Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.