FTP adalah singkatan bahasa Inggris dari protokol transfer file (protokol transfer file), dan singkatan Cina disebut "protokol transfer tertulis". Digunakan untuk transfer dua arah file kontrol di internet. Pada saat yang sama, ini juga merupakan aplikasi. Ada berbagai aplikasi FTP berdasarkan sistem operasi yang berbeda, dan semua aplikasi ini mematuhi protokol yang sama untuk mentransfer file. Dalam penggunaan FTP, pengguna sering menemukan dua konsep: "Unduh" dan "Unggah". File "Unduh" berarti menyalin file dari host jarak jauh ke komputer Anda sendiri; File "mengunggah" berarti menyalin file dari komputer Anda sendiri ke host jarak jauh. Dalam bahasa Internet, pengguna dapat mengunggah (unduh) file ke (dari) host jarak jauh melalui program klien.
Pertama, Serv-U diunduh untuk mengatur komputer Anda sebagai server file FTP untuk pengoperasian yang mudah. Kode berikut digunakan di server FTP dan data yang relevan dari koneksi FTP harus ditulis dalam kode untuk menyelesaikannya.
1. Unggah dan unduh file FTP (perhatikan bahwa itu mengunggah dan mengunduh file individual)
impor java.io.file; impor java.io.fileInputStream; impor java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.ioException; impor java.inputStream; impor java.io.outputstream; impor.apache.apomphe. org.apache.commons.net.ftp.ftpclient; impor org.apache.commons.net.ftp.ftpfile; private static string encoding = System.getProperty ("File.encoding"); /** * Deskripsi: Unggah file ke server ftp * * @version1.0 * @param url * hostname server ftp * port @param * port server ftp * @param nama pengguna * ftp akun login * @param kata sandi FTP * eveade "@param Path * server ftp menyimpan Direktori, jika itu adalah Root Login," Parpar "Ftp Server Simpan Direktori, jika itu adalah ROOK ROOK, ADAT PANDURAN" PARPARAM * FTP Directories * FLEADE FILME, jika itu adalah ROOK ROOK, ADALI LOUPORY "FILPARAM * FTP Directories * FILME FILEDE * FILME FILM * FILME FILM * Server ftp * input @param * aliran input file lokal * @Return return true berhasil, jika tidak, ia akan mengembalikan false */ public static boolean unggahan (string url, int port, string username, kata sandi string, jalur string, nama file string, inputStream input) {boolean hasil = false; coba {int balasan; // Jika Anda menggunakan port default, Anda dapat langsung terhubung ke FTP Server ftpClient.Connect (URL); // ftp.connect (url, port); // hubungkan server ftp // masuk ke ftpclient.login (nama pengguna, kata sandi); ftpClient.setControlencoding (encoding); // Verifikasi bahwa koneksi berhasil Balas = ftpclient.getReplyCode (); if (! ftpreply.ispositiveCompletion (balasan)) {System.out.println ("Koneksi gagal"); ftpclient.disconnect (); hasil pengembalian; } // Transfer Direktori Kerja ke Direktori Boolean Change = ftpClient.ChangeworkingDirectory (PATH); ftpClient.setFileType (ftp.binary_file_type); if (ubah) {result = ftpclient.storefile (string baru (filename.getbytes (encoding), "iso-8859-1"), input); if (result) {System.out.println ("Diunggah dengan sukses!"); }} input.close (); ftpclient.logout (); } catch (ioException e) {e.printstacktrace (); } akhirnya {if (ftpclient.isconnected ()) {coba {ftpclient.disconnect (); } catch (ioException IoE) {}}} hasil pengembalian; }/*** Unggah file lokal ke server ftp**/public void testUploadFromDisk () {coba {fileInputStream in = new fileInputStream (file baru ("d: /test02/list.txt")); bendera boolean = unggahfile ("10.0.0.102", 21, "admin", "123456", "/", "lis.txt", in); System.out.println (flag); } catch (FileNotFoundException e) {e.printstacktrace (); } } /** * Description: Download the file from the FTP server* * @Version1.0 * @param url * FTP server hostname * @param port * FTP server port* @param username * FTP login account* @param password * FTP login password* @param remotePath * Relative path on the FTP server* @param fileName * File name to download * @param localPath * Path to save ke lokal setelah mengunduh * @return */ public static boolean downfile (string url, int port, string nama pengguna, kata sandi string, string remotePath, string fileName, string localpath) {boolean hasil = false; coba {int balasan; ftpClient.setControlencoding (encoding); / * * Untuk mengunggah dan mengunduh file Cina, beberapa tempat merekomendasikan untuk menggunakan dua kalimat berikut, bukan * string baru (remotePath.getbytes (pengkodean), "iso-8859-1") transcoding. * Setelah pengujian, itu tidak dapat dilewati. */// ftpClientConfig conf = ftpClientConfig baru (ftpClientConfig.syst_nt); // conf.setserverlanguagecode ("zh"); ftpclient.connect (url, port); // Jika port default digunakan, Anda dapat langsung terhubung ke server FTP dengan ftpclient.login (nama pengguna, kata sandi); // login // atur jenis transfer file ke ftpclient.setFileType (ftpclient.binary_file_type); // Dapatkan kode respons login FTP Balas = ftpClient.getReplyCode (); // Pastikan login berhasil if (! Ftpreply.ispositiveCompletion (balasan)) {ftpclient.disconnect (); System.err.println ("Server FTP menolak koneksi."); hasil pengembalian; } // Transfer ke direktori server FTP ke direktori yang ditentukan ftpclient.changeworkingdirectory (string baru (remotePath.getbytes (encoding), "iso-8859-1")); // Dapatkan daftar file ftpfile [] fs = ftpclient.listFiles (); untuk (ftpfile ff: fs) {if (ff.getName (). Equals (fileName)) {file localfile = file baru (localpath + "/" + ff.getName ()); OutputStream adalah = FileOutputStream baru (LocalFile); ftpClient.Retrievefile (ff.getName (), IS); is.close (); }} ftpclient.logout (); Hasil = Benar; } catch (ioException e) {e.printstacktrace (); } akhirnya {if (ftpclient.isconnected ()) {coba {ftpclient.disconnect (); } catch (ioException IoE) {}}} hasil pengembalian; }/** * Unduh file di server ftp ke lokal * */public void testdownFile () {coba {boolean flag = downfile ("10.0.0.102", 21, "admin", "123456", "/", "ip.txt", "e:/"); System.out.println (flag); } catch (Exception e) {E.PrintStackTrace (); }} public static void main (string [] args) {ftpapche fa = ftpapche baru (); fa.testdownfile (); fa.testuploadFromDisk (); }}2. Unggah dan unduh folder FTP (perhatikan bahwa seluruh folder adalah seluruh folder)
Paket FTP; Impor java.io.bufferedInputStream; import java.iufferedoutputstream; import java.io.file; impor java.io.fileinputStream; impor java.io.filenotfoundexception; impor java.io. org.apache.commons.net.ftp.ftpclient; impor org.apache.commons.net.ftp.ftpclientConfig; import org.apome.commons.net.ftp.ftpfile; impor org.apache.commons.net.ftp.ftpreply; impor.apache.commons.net.ftp.ftpreply; impor.apache.apome.net.ftp.ftpreply; impor.apache FtpClient ftpClient; strip string pribadi; Private Int Intport; Pengguna String Pribadi; kata sandi string pribadi; private static logger logger = logger.getLogger (ftptest_04.class.getName ()); / * * * Ftp constructor */ public ftptest_04 (string strip, int intor, string user, string password) {this.strip = strip; this.intport = intport; this.user = pengguna; this.password = kata sandi; this.ftpClient = ftpClient baru (); } / *** @return Tentukan apakah login berhasil** / public boolean ftplogin () {boolean islogin = false; FtpClientConfig ftpClientConfig = ftpClientConfig baru (); ftpClientConfig.SetServerTimeZoneID (timezone.getDefault (). getId ()); this.ftpclient.setControlencoding ("GBK"); this.ftpclient.configure (ftpClientConfig); coba {if (this.intport> 0) {this.ftpclient.connect (this.strip, this.intport); } else {this.ftpclient.connect (this.strip); } // ftp server koneksi jawaban int balasan = this.ftpclient.getReplycode (); if (! ftpreply.ispositiveCompletion (balasan)) {this.ftpclient.disconnect (); Logger.Error ("Masuk ke Layanan FTP gagal!"); kembalikan islogin; } this.ftpclient.login (this.user, this.password); // atur protokol transmisi this.ftpclient.enterLocalPassiveMode (); this.ftpclient.setFileType (ftpclient.binary_file_type); logger.info ("ucapan selamat" + this.user + "berhasil masuk ke server FTP"); islogin = true; } catch (Exception e) {E.PrintStackTrace (); Logger.Error (this.user + "Masuk ke layanan FTP gagal!" + E.getMessage ()); } this.ftpclient.setBufferSize (1024 * 2); this.ftpclient.setDataTimeout (30 * 1000); kembalikan islogin; }/ *** @exit tautan tautan server tutup**/ public void ftploGout () {if (null! = This.ftpclient && this.ftpclient.isconnected ()) {coba {boolean reuslt = this.ftpclient.logout (); // exit ftp server if (reussy) {logy (); }} catch (ioException e) {E.PrintStackTrace (); Logger.warn ("Pengecualian Keluar dari Server FTP!" + E.GetMessage ()); } akhirnya {coba {this.ftpclient.disconnect (); // tutup koneksi ke server ftp} catch (ioException e) {e.printstacktrace (); logger.warn ("Pengecualian menutup koneksi server FTP!"); }}}}}/**** Unggah file ftp* @param localfile file lokal* @param romoTuploadepath Jalur server unggah- harus diakhiri dengan/*//unggahan boolean publik (file localfile, string romotuploadepath) {bufferedInputStream instream = null; Boolean Success = false; coba {this.ftpclient.changeworkingdirectory (romotuploadepath); // Ubah jalur kerja instream = new bufferedInputStream (FileInputStream baru (localfile)); logger.info (localfile.getName () + "Mulai unggah ..."); Success = this.ftpclient.storefile (localfile.getName (), instream); if (success == true) {logger.info (localfile.getName () + "diunggah dengan sukses"); Sukses kembali; }} catch (FileNotFoundException e) {e.printstacktrace (); Logger.Error (localfile + "tidak ditemukan"); } catch (ioException e) {e.printstacktrace (); } akhirnya {if (instream! = null) {coba {instream.close (); } catch (ioException e) {e.printstacktrace (); }}} Return Success; } /*** * Download file* @param remoteFileName File name to be downloaded* @param localDires Download to the local path* @param remoteDownLoadPath The path where remoteFileName is located* */ public boolean downloadFile(String remoteFileName, String localDires, String remoteDownLoadPath) { String strFilePath = localDires + remoteFileName; BufferedOutputStream outstream = null; Boolean Success = false; coba {this.ftpClient.ChangeworkingDirectory (RemotedownloadPath); outstream = baru bufferedoutputStream (fileoutputStream baru (strfilePath)); Logger.info (RemoteFileName + "Mulai Unduh ..."); Success = this.ftpClient.Retrievefile (RemoteFileName, outstream); if (Success == true) {logger.info (RemoteFileName + "berhasil diunduh ke" + strfilePath); Sukses kembali; }} catch (Exception e) {e.printstacktrace (); Logger.Error (RemoteFileName + "Unduh Gagal"); } akhirnya {if (null! = outstream) {coba {outstream.flush (); outstream.close (); } catch (ioException e) {e.printstacktrace (); }}} if (success == false) {logger.error (RemoteFileName + "Unduh Gagal !!!"); } mengembalikan kesuksesan; }/**** @upload folder* @param localdirectory* folder lokal* @param remoteDirectoryPath* jalur server ftp berakhir dengan direktori "/"*/public boolean unggahdirectory (string localdirectory, string remotedirectorypath) {file src = newDirectory, string remotedirectorypath) {file src = newDirectory (string remotedirectoryPath) {file src = newDirectore (localdirectory); coba {remoteDirectoryPath = remoteDirectoryPath + src.getName () + "/"; boolean makedirflag = this.ftpclient.makedirectory (remotedirectorypath); System.out.println ("LocalDirectory:" + LocalDirectory); System.out.println ("RemoteDirectoryPath:" + RemoteDirectoryPath); System.out.println ("src.getName ():" + src.getName ()); System.out.println ("RemoteDirectoryPath:" + RemoteDirectoryPath); System.out.println ("Makedirflag:" + Makedirflag); // ftpclient.listdirectories (); } catch (ioException e) {e.printstacktrace (); Logger.info (RemoteDirectoryPath + "Kreasi Direktori Gagal"); } File [] allfile = src.listFiles (); untuk (int currentFile = 0; currentFile <allfile.length; currentFile ++) {if (! allfile [currentFile] .isdirectory ()) {string srcname = allfile [currentFile] .getPath (). tostring (); unggahfile (file baru (SRCNAME), RemoteDirectoryPath); } } for (int currentFile = 0;currentFile < allFile.length;currentFile++) { if (allFile[currentFile].isDirectory()) { // Recursive uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath); }} return true; } / **** @Download folder* @param localdirectorypath alamat lokal* @param folder jarak jauh remoteDirectory** / public boolean downloaddirectory (string localdirectorypath, string remoteDirectory) {coba {string fileName = file baru (remoteDirectory) .getName (); localdirectorypath = localdirectorypath + fileName + "//"; file baru (localdirectorypath) .mkdirs (); Ftpfile [] allFile = this.ftpclient.listFile (remoteDirectory); untuk (int currentFile = 0; currentFile <allfile.length; currentFile ++) {if (! allfile [currentFile] .isdirectory ()) {downloadfile (allfile [currentFile] .getName (), localdirectorypath, remoteDirectory); }} untuk (int currentFile = 0; currentFile <allfile.length; currentFile ++) {if (allFile [currentFile] .isdirectory ()) {string strremotedirectoryPath = remoteDirectory+ "/"+ allFile [currentFile] .getName (); downloaddirectory (localdirectorypath, strremotedirectorypath); }}} catch (ioException e) {E.PrintStackTrace (); Logger.info ("Folder Unduh Gagal"); mengembalikan false; } return true; } // ftpClient set dan dapatkan fungsi publik ftpClient getFtpClient () {return ftpClient; } public void setFtpClient (ftpClient ftpClient) {this.ftpClient = ftpClient; } public static void main (string [] args) melempar ioException {ftptest_04 ftp = ftptest_04 baru ("10.0.0.102", 21, "admin", "123456"); ftp.ftplogin (); System.out.println ("1"); // unggah folder boolean unggahflag = ftp.uPloaddirectory ("d: // test02", "/"); // Jika admin/, maka semua file dilewatkan. Jika hanya/, maka itu diteruskan pada folder System.out.println ("UploadFlag:" + unggahflag); // unduh folder ftp.downloadDirectory ("d: // tm", "/"); ftp.ftplogout (); }}Di atas adalah semua konten artikel ini. Saya berharap konten artikel ini akan membantu untuk belajar atau bekerja semua orang. Saya juga berharap untuk mendukung wulin.com lebih lanjut!