In this section, you will learn how to check existence of a file on the server by using java.
Check existence of a File :
You can check the existence of a file on FTP server. FTPClient class helps to list all the files and directory on the FTP server by using method listFile(). By using isFile() method of FTPFile class, you can check that there is any file present or not.
Here is some steps to check existence of a file -
1. Connect and login to the FTP server.
client.connect("localhost");
client.login("admin", "admin");
2. List all the files and directories of FTP server and store on FTPFile array.
FTPFile[] files = client.listFiles();
3. Now iterate the files and put condition to check for file.
for (FTPFile file : files) {
if (file.isFile())
4. For counting the number of files in FTP server you can use counter variable and increment each time you found file.
boolean isFile() : This method returns true if file found otherwise returns false.
Example :
This example checks the existence of file on the server and also print the number of files found on the server.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
class FtpFileExistenceCheck {
public static void main(String[] args) throws IOException {
FTPClient client = new FTPClient();
boolean result;
try {
// Connect to the localhost
client.connect("localhost");
// login to ftp server
result = client.login("admin", "admin");
if (result == true) {
System.out.println("User successfully logged in.");
} else {
System.out.println("Login failed!");
return;
}
// List all files and directories
FTPFile[] files = client.listFiles();
int count = 0;
System.out.println("Checking file existence on the server ... ");
// Check for file existence
for (FTPFile file : files) {
if (file.isFile()) {
count++;
}
}
if (count > 0) {
System.out.println(count + " files found on FTP server. ");
} else {
System.out.println("Sorry! There is no file found on Ftp server.");
}
} catch (FTPConnectionClosedException e) {
System.out.println(e);
} finally {
try {
client.disconnect();
} catch (FTPConnectionClosedException e) {
System.out.println(e);
}
}
}
}
Output :
User successfully logged in. Checking file existence on the server ... 5 files found on FTP server.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Checking File existence on Ftp Server
Post your Comment