preparation
1. Set up the Ftp server
To facilitate the local test, you can set up the Ftp server on the local server first. There are many tutorials for setting up an Ftp server, and I won’t go into them here, but here are the tutorials that I use and you can look at them. Win10 怎 么 build FTP server
Some points to note:
- When assigning permissions, allow “read and write” to ensure smooth uploading and downloading.
- Do not use anonymous login, otherwise the FTPClient will fail to connect during the test.
- After you build it, you can test it by connecting to another computer for uploading, downloading and deleting.
2. Import related packages
To implement these features, you use an FTPClient class that imports the Commons-net-3.6 package externally. If it’s not a Maven project, you can only download the package from the network. The download address is as follows
If it is a Maven project, just add the dependencies:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
Copy the code
Ps: If you need other packages, you can go to this website to find how to write dependencies. mvnrepository.com/
Officially open yards
1. Connection to the Ftp server
Before connecting to the FTP server, use the following parameters. You can write them directly or read them from the configuration file if you need to change them frequently.
Ps: Relevant parameters are filled in their own, I here is to give an example of the filler.
private static FTPClient ftpClient; // Create an object
private static String ip = "192.168.0.1"; / / FTP address
private static Integer port = 21; // The default FTP port number is 21
private static String userName = "Veggie"; / / user name
private static String passWord = "root"; / / password
Copy the code
The next step is to perform initialization operations, including quantity initialization, connection, and login. Possible causes of connection failure:
- Not in the same LAN, the connection must be in the same LAN.
- Displays that the connection has been reset. You can optionally restart the Ftp server using IIS Manager. If not, you can delete the Ftp created first and then create it again.
public static boolean initFtpClient(a) throws Exception {
boolean is_success = false;
int reply;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip, port); // Connect to the Ftp server
ftpClient.login(userName, passWord); Log in to the Ftp server
ftpClient.setControlEncoding("utf-8");// Set the encoding type
reply = ftpClient.getReplyCode(); // Obtain the return code to determine whether the connection is successful
if(! FTPReply.isPositiveCompletion(reply)) {throw new Exception("Server connection failed");
} else {
ftpClient.enterLocalPassiveMode(); // Set passive mode
ftpClient.setControlEncoding("GBK");// Set character mode to solve Chinese garbled characters
is_success = true; }}catch (Exception e) {
e.printStackTrace();
}
return is_success;
}
Copy the code
Although I did not close the connection after the operation was completed, it still makes sense to close the connection, so let’s call it.
public static void dropFtpClient(a) {
try {
ftpClient.logout(); // Log out
if (ftpClient.isConnected()) {// Check whether the Ftp server is connected
ftpClient.disconnect(); // Close the connection}}catch(IOException e) { e.printStackTrace(); }}Copy the code
2. Upload the file
If there is a problem with the upload, it is possible that the “write” permission for the connection is not enabled.
/** * Upload file **@paramPathname Saving address of the FTP service *@paramOriginfilename Specifies the name (absolute address) of the file to be uploaded@return* /
public static boolean uploadFile(String pathname, String originfilename) {
boolean is_success = false;
InputStream inputStream = null;
try {
File localFile = new File(originfilename);
inputStream = new FileInputStream(localFile);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(pathname); // Jump to the specified Ftp file directory (relative path)
is_success = ftpClient.storeFile(localFile.getName(), inputStream);// Upload the file
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return is_success;
}
Copy the code
3. Download operations
This download operation is to download all the files in the path, or according to their needs to download a specific file. Accordingly, if the download fails without argument passing problems, check to see if there is a “read” permission.
/* * Downloaded file * * @param pathName FTP server file directory * @param localPath Downloaded file path * * @return */
public static boolean downloadFile(String pathName, String localPath) {
boolean is_success = false;
OutputStream os = null;
try {
ftpClient.changeWorkingDirectory(pathName);// Go to the specified Ftp file directory
FTPFile[] ftpFiles = ftpClient.listFiles();// Get all files and folders in the directory
// Traverse all files in the directory
for (FTPFile file : ftpFiles) {
if (file.isFile()) {
File localFile = new File(localPath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);// Download the file locally
os.close();
} else if (file.isDirectory()) {
downloadFile(pathName + file.getName() + "/", localPath);
}
}
is_success = true;
} catch (Exception e) {
e.printStackTrace();
}
return is_success;
}
Copy the code
4. Delete
If both of the above operations work, then deleting will generally work as well.
/* * delete file * * @param pathName FTP server file directory * @param fileName fileName to delete * @return */
public static boolean deleteFile(String pathNmae, String fileName) {
boolean is_success = false;
try {
ftpClient.changeWorkingDirectory(pathNmae);
is_success = ftpClient.deleteFile(fileName);// Delete the file
} catch (Exception e) {
e.printStackTrace();
}
return is_success;
}
Copy the code
test
Although much of the exception handling has been removed to simplify the code, it can be done under normal circumstances. There are so many features that need to be tested, and you can see that our test steps are:
- Initialize FtpClient
- Download all files from the Ftp server to the local PC
- Delete “1.jpg” from Ftp
- Upload the downloaded “1.jpg” image to the Ftp server
- Log out and close the connection
public static void main(String[] arg) throws Exception {
boolean is_success = false;
// Initialize FtpClient
is_success = initFtpClient();
System.out.println(is_success);
// Download all files from Ftp to local
is_success=downloadFile("/"."D:\\test0");
System.out.println(is_success);
// Delete the specified file from Ftp
is_success = deleteFile("/"."1.jpg");
System.out.println(is_success);
// Upload the local file to the Ftp server
is_success = uploadFile("/"."D:\\test0\\1.jpg");
System.out.println(is_success);
// Log out and close the connection
dropFtpClient();
}
Copy the code
By looking at the messages coming back from the console and seeing that I had no problems testing it on my computer, I could go to the folder and see if it was really successful.// After a look, it is indeed successful
The resources
About this reference material, I have always felt very crass, in the information on the Internet to find 50 percent of the content are the same, and all marked original (said that the original at least have something of their own). Some also directly copy the other people’s content directly, also do not mark the source, even the format is too lazy to once, I was drunk, began to have a sense of disgust this behavior. Blog.csdn.net/lht93194278…