要批量上傳文件到服務(wù)器,可以使用Java中的FTP客戶端庫(kù)來(lái)實(shí)現(xiàn)。以下是一個(gè)使用Apache Commons Net庫(kù)的示例代碼:
importorg.apache.commons.net.ftp.FTP;importorg.apache.commons.net.ftp.FTPClient;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;publicclassFTPUploader{privatestaticfinalStringSERVER="ftp.example.com";privatestaticfinalintPORT=21;privatestaticfinalStringUSERNAME="username";privatestaticfinalStringPASSWORD="password";publicstaticvoidmain(String[]args){FTPClientftpClient=newFTPClient();try{ ftpClient.connect(SERVER,PORT); ftpClient.login(USERNAME,PASSWORD);ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode();Filedirectory=newFile("path/to/directory"); File[]files=directory.listFiles();if(files!=null){for(Filefile:files){if(file.isFile()){StringremoteFile=file.getName();FileInputStreaminputStream=newFileInputStream(file);ftpClient.storeFile(remoteFile,inputStream); inputStream.close();System.out.println("Uploadedfile:"+remoteFile); } } }ftpClient.logout(); }catch(IOExceptione){ e.printStackTrace(); }finally{try{ ftpClient.disconnect(); }catch(IOExceptione){ e.printStackTrace(); } } } }
在代碼中,需要替換以下變量的值:
SERVER
:FTP服務(wù)器地址PORT
:FTP服務(wù)器端口號(hào)USERNAME
:FTP登錄用戶名PASSWORD
:FTP登錄密碼"path/to/directory"
:要上傳的文件所在的本地目錄路徑
代碼首先創(chuàng)建一個(gè)FTPClient實(shí)例,并使用connect
方法連接到FTP服務(wù)器。然后使用login
方法進(jìn)行登錄。接下來(lái),設(shè)置文件傳輸類型為二進(jìn)制,并進(jìn)入本地被動(dòng)模式。然后,通過(guò)listFiles
方法獲取本地目錄中的文件列表。對(duì)于每個(gè)文件,使用storeFile
方法將文件上傳到服務(wù)器,并使用close
方法關(guān)閉文件流。最后,使用logout
方法登出并斷開(kāi)與服務(wù)器的連接。