Java File retrieving from FTP server - java

I am trying to retrieve a file from ftp server but I get error as below. Would you please help me
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream.GetField;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FtpTest_V1 {
public static void main(String[] args) {
String server = "192.168.200.8";
int port = 21;
String user = "Test_user";
String pass = "123456**";
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
ftpClient.enterLocalPassiveMode();
int replyCode = ftpClient.getReplyCode();
System.out.println(replyCode);
//isPositiveCompletion
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println(FTPReply.isPositiveCompletion(replyCode));
System.out.println(FTPReply.isNegativeTransient(replyCode));
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
//System.out.println(success);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
// Lists files and directories
FTPFile[] files1 = ftpClient.listFiles("TEST2");
//printFileDetails(files1);
// uses simpler methods
String[] files2 = ftpClient.listNames("TEST2");
printNames(files2);
String[] files = files2;
for (String aFile: files) {
String filename = aFile;
fos = new FileOutputStream(filename);
// Download file from FTP server
ftpClient.retrieveFile("C://test//FTP_TEST//GET" + filename, >fos);
}
}
catch (IOException ex) {
System.out.println("An Error Occured"+ex.getMessage());
System.out.println("Warning! Something wrong happened");
ex.printStackTrace();
} finally {
// logs out and disconnects from server
try {
if (fos != null) {
fos.close();
}
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void printNames(String files[]) {
if (files != null && files.length > 0) {
int i =0;
for (String aFile: files) {
i++;
}
System.out.println("Number of files = "+i);
for (String aFile: files) {
System.out.println(aFile);
}
}
}
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER : " + aReply);
}
}
}
}
Here is my Output :
SERVER : 220-FileZilla Server version 0.9.43 beta
SERVER : 220 Hello FTP SERVER
220
SERVER : 230 Logged on
number of files = 2
TEST2/testfile.csv
TEST2/tttt.csv
An Error OccuredTEST2\testfile.csv (The system cannot find the path specified)
Warning! Something wrong happened
java.io.FileNotFoundException: TEST2\testfile.csv (The system cannot find the path
specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.(Unknown Source)
at java.io.FileOutputStream.(Unknown Source)
at FtpTest_V1.main(FtpTest_V1.java:74)

The slash should be backwards like this: "C:\ \test\ \FTP_TEST\ \GET" (without the middle space, I put it that way because the html parser in this page change it to only one slash)
intead of:
ftpClient.retrieveFile("C://test//FTP_TEST//GET" + filename, >fos);
Or even better:
"C:" + File.separatorChar + "test" + File.separatorChar + "FTP_TEST" + File.separatorChar + "GET"

Hello I have solved the problem as changing the code. try catch block is as below
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String[] files = ftpClient.listNames("TEST_FILE");
for (String aFile: files) {
String remoteFile1 = aFile;
File downloadFile1 = new File("C:/test/FTP_TEST
/GET/"+remoteFile1.replace("TEST_FILE", ""));
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
System.out.println("File #1 has been downloaded successfully.");
}
}

Related

Trouble writing to OutputStream socket

I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.

Connection Refused Error Coming At The Time Of Uploading Files From Local Machine To FTP Server

I am trying to upload files from local machine to ftp server and when this code starts first it store 6 folder data sucessfully on ftp server but from 7th folder to 25th folder i am getting connection refused error ... There is no limitation from client side for connections and only i am using these credentials for testing purpose . Can any one help me?
I am getting this issue because of mirror issue in code but i am not able to figureout this issue. Please help me
package com.epath.smoketest.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPSClient;
public class FTPUploadDirectoryTest {
public static void main(String[] args) {
try {
System.out.println("\n"
+ "---------------------------------------------------------------------------------" + "\r\n");
System.out.println("Read FTP Login details from PROPERTIES file" + "\r\n");
System.out.println(
"---------------------------------------------------------------------------------" + "\r\n");
Properties prop = new Properties();
InputStream input = null;
String inputFS = getAutomationInputDataPath() + "//Validation.properties";
input = new FileInputStream(inputFS);
prop.load(input);
// -Input file with test data
System.out.println("Uploading file on ftp server");
String ftp_port = prop.getProperty("ftp_port");
int ftp_host = Integer.parseInt(prop.getProperty("ftp_host"));
String ftp_username = prop.getProperty("ftp_username");
String ftp_password = prop.getProperty("ftp_password");
String server = ftp_port;
int port = ftp_host;
String user = ftp_username;
String pass = ftp_password;
FTPSClient ftpClient = new FTPSClient();
// connect and login to the server
ftpClient.connect(server, port);
ftpClient.login(user, pass);
// use local passive mode to pass firewall
ftpClient.enterLocalPassiveMode();
System.out.println("Connected");
String remoteDirPath = "/www/ngage/screenshots";
String localDirPath = folderPathForUploadingOnFTP;
uploadDirectory(ftpClient, remoteDirPath, localDirPath, "");
// log out and disconnect from the server
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Disconnected");
} catch (IOException ex) {
System.err.println("Error occured....." + ex.getMessage());
ex.printStackTrace();
}
}
public static void uploadDirectory(FTPSClient ftpClient, String remoteDirPath, String localParentDir,
String remoteParentDir) throws IOException {
File localDir = new File(localParentDir);
File[] subFiles = localDir.listFiles();
if (subFiles != null && subFiles.length > 0) {
for (File item : subFiles) {
String remoteFilePath = remoteDirPath + "/" + remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
remoteFilePath = remoteDirPath + "/" + item.getName();
}
if (item.isFile()) {
if (!checkFileExists(remoteFilePath, ftpClient)) {
// upload the file
String localFilePath = item.getAbsolutePath();
boolean uploaded = uploadSingleFile(ftpClient, localFilePath, remoteFilePath);
if (uploaded) {
System.out.println("UPLOADED a file to: " + remoteFilePath);
} else {
System.out.println("COULD NOT upload the file: " + localFilePath);
}
} else {
System.out.println("This file alerady exist on ftp server ");
}
} else {
// create directory on the server
boolean created = ftpClient.makeDirectory(remoteFilePath);
if (created) {
System.out.println("CREATED the directory: " + remoteFilePath);
} else {
System.out.println("COULD NOT create the directory: " + remoteFilePath);
}
// upload the sub directory
String parent = remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
parent = item.getName();
}
localParentDir = item.getAbsolutePath();
uploadDirectory(ftpClient, remoteDirPath, localParentDir, parent);
}
}
}
ftpClient.makeDirectory(remoteDirPath);
}
public static boolean uploadSingleFile(FTPSClient ftpClient, String localFilePath, String remoteFilePath)
throws IOException {
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.storeFile(remoteFilePath, inputStream);
} finally {
inputStream.close();
}
}
public static Boolean checkFileExists(String filePath, FTPSClient ftpClient) throws IOException {
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
int returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
return false;
}
inputStream.close();
return true;
}
}
Error coming .
COULD NOT upload the file: \\192.168.10.21\volume1\ngage_dev\engineering\ngage\testing\automated\validation\Build_1.19.1\051\2018-04-23_07-54-39_AM\TC_UA_PSWD_0001_006_1.png
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:920)
at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:627)
at org.apache.commons.net.ftp.FTPClient._retrieveFileStream(FTPClient.java:1980)
at org.apache.commons.net.ftp.FTPClient.retrieveFileStream(FTPClient.java:1967)
at com.epath.smoketest.tests.FTPUploadDirectoryTest.checkFileExists(FTPUploadDirectoryTest.java:124)

Download a files from FTP matching a wildcard using Java Apache Commons Net

Basically I need to download list of matching files for the search from a FTP server. I have the code to download a specific file from a FTP server. But I need to download all the matching files with my wildcard search. How is that possible in Java?
Here is code for file downloading of a specific filename, from a FTP server -
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FTPDownloadFileDemowithoutmodandfilefilter {
public static void main(String[] args) {
String server = "test.rebex.net";
int port = 21;
String user = "demo";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File localFile = new File("C:\\project\\readme1.txt");
FTPFile remoteFile = ftpClient.mdtmFile("/readme.txt");
if (remoteFile != null)
{
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(localFile));
if (ftpClient.retrieveFile(remoteFile.getName(), outputStream))
{
System.out.println("File downloaded successfully.");
}
outputStream.close();
localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Use FTPClient.mlistDir (recommended, if the server supports it) or
FTPClient.listFiles to retrieve list of files. And then filter them according to your needs.
The following example downloads all files matching a regular expression .*\.jpg:
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
Pattern pattern = Pattern.compile(".*\\.jpg");
Stream<FTPFile> matchingFiles =
Arrays.stream(remoteFiles).filter(
(FTPFile remoteFile) -> pattern.matcher(remoteFile.getName()).matches());
for (Iterator<FTPFile> iter = matchingFiles.iterator(); iter.hasNext(); ) {
FTPFile remoteFile = iter.next();
System.out.println("Found file " + remoteFile.getName() + ", downloading ...");
File localFile = new File(localPath + "\\" + remoteFile.getName());
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(localFile));
if (ftpClient.retrieveFile(remotePath + "/" + remoteFile.getName(), outputStream))
{
System.out.println(
"File " + remoteFile.getName() + " downloaded successfully.");
}
outputStream.close();
}

FTP File upload Exception 'Software caused connection abort: recv failed' -JAVA

I am trying to upload multiple directories to FTP but after 4-5 minutes of uploading stared I am getting 'Software caused connection abort: recv failed' exception only a few files got uploaded. I checked the FTP Time out settings it is set to 10 minutes and also tried both enterLocalPassiveMode() and sendNoOp() but didn't work please help me to fix this.
public class FTPUpload {
public void initFtpupload(String localparentDir,String batchno) //not in use
{
try {
readProperty();
CreateFile();
localDirPath=localparentDir;
lotno=batchno;
FTPUpload ftpobj = new FTPUpload(ftpIp, ftpPort, ftpUname, ftpPassword);
System.out.println("Local Dir PAth:"+localparentDir);
System.out.println("Local dir path: "+localDirPath);
ftp.changeWorkingDirectory(ftpRootDir);
if(true)
{
IterateDirectory(localDirPath);
}
ftpobj.disconnect();
} catch (Exception e) {
String error=stackTraceToString(e);
genLog("Exception in InitFtpUpload: "+e);
System.out.println("Exception:" + e);
genLog("Exception Trace:" + error);
}
}
// Constructor to connect to the FTP Server
public FTPUpload(String host, int port, String username, String password) throws Exception {
java.util.Date dtCurDate = new java.util.Date();
SimpleDateFormat sdfDate = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
String strCurDate = sdfDate.format(dtCurDate);
String strLogPath = System.getProperty("user.dir") + File.separator + "Log";
String strLogFilePath = strLogPath + File.separator + "FTPConnectionLog_" + strCurDate + ".log";
File logfile=new File(strLogFilePath);
ftp = new FTPClient();
//ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(logfile)));
int reply;
ftp.connect(host, port);
System.out.println("FTP URL is:" + ftp.getDefaultPort());
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
genLog("Exception in connecting to FTP Server");
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
genLog("Connected");
System.out.println("Connected ");
}
// list the files in a specified directory on the FTP
public static boolean IterateDirectory(String localRootDirectoryPath) throws IOException {
// lists files and directories in the current working directory
//for test
ftp.changeWorkingDirectory(ftpRootDir);
System.out.println("Inside IterateDirectory ");
FTPFile dirs[]=ftp.listFiles();
for(FTPFile f:dirs)
{
System.out.println("####"+f);
}
//upto this...
boolean verificationFilename = false;
String newFtpDirectoy = "";
File localfile = new File(localRootDirectoryPath);
File files[] = localfile.listFiles();
for (File file : files) {
String details = file.getName();
if (file.isDirectory()) {
IterateDirectory(file.getPath());
iflag=false;
} else {
if (iflag == false) {
localRootDirectoryPath = file.getParent();
newFtpDirectoy = localRootDirectoryPath.substring(localRootDirectoryPath.indexOf("HUB"));
newFtpDirectoy = newFtpDirectoy.replaceAll("\\\\", "/");
if (true) {
makeDirectories(ftp, newFtpDirectoy);
String localParenDir = file.getParent();
genLog("ftpDirPath: "+ftpDirPath);
genLog("New FTP Dir: "+newFtpDirectoy);
genLog("Local parent dir: "+localParenDir);
System.out.println("ftpDirPath: "+ftpDirPath);
System.out.println("New FTP Dir: "+newFtpDirectoy);
System.out.println("Local parent dir: "+localParenDir);
uploadDirectory(ftp, ftpDirPath, localParenDir, newFtpDirectoy);
mailist.add(localRootDirectoryPath);
File f=new File(localRootDirectoryPath);
String finalPath=f.getParent();
if(!mailistlocal.contains(finalPath)){
mailistlocal.add(finalPath);
}
}
iflag = true;
}
}
}
return true;
}
// Disconnect the connection to FTP
public void disconnect() {
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already saved to server
}
System.out.println("FTP Disconnected successfully");
genLog("FTP Disconnected successfully");
}
}
}
}
}
}
You might want to consider using an existing library rather than creating your own. For example: https://commons.apache.org/proper/commons-net/
https://commons.apache.org/proper/commons-net/javadocs/api-1.4.1/org/apache/commons/net/ftp/FTPClient.html
EDIT (Added working example):
This code worked for me using the jar file found here: https://commons.apache.org/proper/commons-net/download_net.cgi
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.net.tftp.TFTP;
import org.apache.commons.net.tftp.TFTPClient;
public class FtpExample {
public static void main(String[] args) throws Exception {
String fileName = "C:\\TEMP\\MyTestFile.txt";
String hostName = "speedtest.tele2.net";
String remoteFileName = "upload/MyTestFile.txt";
File file = new File(fileName);
System.out.println("Sending file: " + file.getName() + "(exists: " + file.exists() + ")");
sendFile(file, hostName, remoteFileName);
System.out.println("Done!");
}
private static void sendFile(File file, String hostName, String remoteFileName) {
TFTPClient tftp = null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
tftp = new TFTPClient();
tftp.open();
tftp.sendFile(remoteFileName, TFTP.BINARY_MODE, inputStream, hostName);
} catch (Exception exp) {
throw new RuntimeException(exp);
} finally {
try {
if (tftp != null) {
tftp.close();
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
}
}
}
I got the same error
Software caused connection abort
From a FTP client perspective, the server was closing my connection after successful authentication, because my ip was no whitelisted in the ftp server cloud provider.
After whitelisting my public IP, I could connect to FTP server succesfully.

What does the error "Usage: java ftp.ftp try Properties_file" mean in Java?

I have a java API for FTP client. I downloaded the jar files that support this FTP API. For some reason, a Usage: java ftp.ftptry Properties_file error was detected.
Here is my code:
package ftp;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class ftptry {
static Properties props;
public static void main(String[] args) {
ftptry getMyFiles = new ftptry();
if (args.length < 1)
{
System.err.println("Usage: java " + getMyFiles.getClass().getName()+
" Properties_file");
System.exit(1);
}
String propertiesFile = args[0].trim();
getMyFiles.startFTP(propertiesFile);
}
public boolean startFTP(String propertiesFile){
props = new Properties();
try {
props.load(new FileInputStream("properties/" + propertiesFile));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
String localDirectory = props.getProperty("localDirectory").trim();
//new ftp client
FTPClient ftp = new FTPClient();
//try to connect
ftp.connect(serverAddress);
//login to server
if(!ftp.login(userId, password))
{
ftp.logout();
return false;
}
int reply = ftp.getReplyCode();
//FTPReply stores a set of constants for FTP reply codes.
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
return false;
}
//enter passive mode
ftp.enterLocalPassiveMode();
//get system name
System.out.println("Remote system is " + ftp.getSystemType());
//change current directory
ftp.changeWorkingDirectory(remoteDirectory);
System.out.println("Current directory is " + ftp.printWorkingDirectory());
//get list of filenames
FTPFile[] ftpFiles = ftp.listFiles();
if (ftpFiles != null && ftpFiles.length > 0) {
//loop thru files
for (FTPFile file : ftpFiles) {
if (!file.isFile()) {
continue;
}
System.out.println("File is " + file.getName());
//get output stream
OutputStream output;
output = new FileOutputStream(localDirectory + "/" + file.getName());
//get the file from the remote system
ftp.retrieveFile(file.getName(), output);
//close output stream
output.close();
//delete the file
ftp.deleteFile(file.getName());
}
}
ftp.logout();
ftp.disconnect();
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
return true;
}
}
and my properties file contains:
#Properties File FTP to server
serverAddress=192.168.xxx.xxx
userId=xxx
password=xxx
remoteDirectory=/LogFiles
localDirectory=/LogFiles
What does this error mean? and how will I run this program without this error?
You need to provide the name of the property file on the command line when invoking your application.
(You need to understand how the check on args.length works)

Categories

Resources