I am using org.apache.commons.net.ftp.FTPClient for downloading files from ftp server.
It downloads all the files from my ftp server except those files with names like test.xml test.txt west.xml etc., The files with these names are getting downloaded with no data inside the file. retrieveFile() method is returning boolean false for these files.
I tried to download the same file by renaming its name manually on ftp server. It worked well with other names.
Please let me know how to solve this problem.
EDIT- Adding sample code
public static boolean downloadFTPDir(String localDir, FTPClient ftpClient) {
OutputStream output = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
/*
* Use passive mode as default because most of us are behind
* firewalls these days.
*/
ftpClient.enterLocalPassiveMode();
FTPFile[] fileList = ftpClient.listFiles();
for (FTPFile ftpFile : fileList) {
if(ftpFile.isDirectory()){
String tempDir = localDir + File.separatorChar+ftpFile.getName();
try {
File temp = new File(tempDir);
temp.mkdirs();
} catch (Exception e) {
System.out.println("Could not create local directory "+tempDir);
return false;
}
if(ftpClient.changeWorkingDirectory(ftpFile.getName())) {
downloadFTPDir(tempDir, ftpClient);
} else {
System.out.println("Could change directory to "+ftpFile.getName()+" on FTP server");
return false;
}
} else {
output = new FileOutputStream(localDir + File.separatorChar + ftpFile.getName());
if (!ftpClient.retrieveFile(ftpFile.getName(), output)) {
System.out.println("Unable to download file from FTP server : " + ftpFile.getName());
File tmp = null;
try {
output.close();
/*tmp = new File(localDir + File.separatorChar + ftpFile.getName());
tmp.delete();
logger.info("Deleted corrupt downloaded file : " + tmp.getAbsolutePath());*/
} catch (FTPConnectionClosedException e) {
System.out.println("Connection to FTP server is closed ");
return false;
} catch (Exception e1) {
System.out.println("Unable to delete corrupt file from local directory : " + tmp.getAbsolutePath());
return false;
}
}
output.close();
System.out.println("FTP file download successful : " + ftpFile.getName());
}
}
} catch (FTPConnectionClosedException e) {
e.printStackTrace();
return false;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return false;
} catch (IOException e2) {
e2.printStackTrace();
return false;
} catch (Exception e3) {
try {
output.close();
} catch (Exception e4) {
e3.printStackTrace();
}
return false;
} finally{
try {
if(output!=null)
output.close();
} catch (Exception e5) {
e5.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("FTP IP", 21);
System.out.println("connecting");
if(FTPReply.isPositiveCompletion(ftpClient.getReply())) {
System.out.println("connected");
if(!ftpClient.login("FTP username", "FTP Password")) {
System.out.println("could not login");
ftpClient.disconnect();
return;
}
System.out.println("logged in");
String remotePath = "FTP directory Path";
StringTokenizer st = new StringTokenizer(remotePath, "/");
String dir = null;
boolean status = false;
while (st.hasMoreTokens()) {
dir = st.nextToken();
status = ftpClient.changeWorkingDirectory(dir);
if (!status) {
System.out.println("FTP client is not able to change the current directory to " + dir);
return ;
}
}
System.out.println("connected");
downloadFTPDir("local path", ftpClient);
} else {
ftpClient.disconnect();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I'm trying to connect to my FTP server in Java SE 1.8. To do so I use this method :
private void connectFTP() {
String server = "ftp.XXXXXXXXXX.site";
int port = 21;
String user = "XXXX";
String pass = "XXXX";
if(!ftpConnexionSuccess.get())
{
client = new FTPClient();
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
try {
client.connect(server, port);
ftpConnexionSuccess.set(client.login(user, pass));
if (!ftpConnexionSuccess.get()) {
System.out.println("Could not login to the server");
return;
}
else
{
System.out.println("LOGGED IN SERVER");
client.changeWorkingDirectory("/crypto");
listenedFile = getListenedFile();
System.out.println(listenedFile.getName());
if(listenedFile != null)
{
baseFileTimeStamp.set(listenedFile.getTimestamp().getTimeInMillis());
}
System.out.println(baseFileTimeStamp);
}
} catch (Exception ex) {
System.err.println("FTP connection error : Sleeping for 5 seconds before trying again (" + ex.getMessage() + ")");
ex.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();}
try {
client.disconnect();
} catch (IOException e) {e.printStackTrace();}
connectFTP();
}
}
}
It works great when I'm on Eclipse and when I export the app on my Windows 10.
Nonetheless, when I try to launch the app on my AWS Webmachine I get a null pointer exception at "listenedFile". The method to listen to this file is the one below.
private FTPFile getListenedFile() {
FTPFile returnedFile = null;
try {
for(FTPFile file : client.listFiles())
{
if(file.getName().contains("filetolisten.txt"))
returnedFile = file;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
try {
client.disconnect();
} catch (IOException e1) {e1.printStackTrace();}
connectFTP();
return getListenedFile();
}
return returnedFile;
}
I thought it was because of the line
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked.
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked. Also updated Java, updated the common-nets library. Nothing worked
I am trying to the properties from java.util.Properties to a online file using its URL.
This is the code I have so far:
public static boolean savePropertiesToURL(Properties properties, String link, String fileName) {
boolean result = false;
if (properties != null && link != null && fileName != null) {
try {
URL url = new URL(link);
try {
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
try {
OutputStream outStream = connection.getOutputStream();
try {
properties.store(outStream, fileName);
} catch (IOException ex) {
System.err.println("Unable to store the properties: " + ex.getMessage());
} finally {
try {
outStream.flush();
result = true;
} catch (IOException ex) {
Logger.getLogger(PropertiesUtil.class.getName()).log(Level.SEVERE, null, ex);
System.err.println("Unable to flush outputstream: " + ex.getMessage());
}
outStream.close();
}
} catch (IOException ex) {
System.err.println("Unable to get outputstream: " + ex.getMessage());
}
} catch (IOException ex) {
System.err.println("Unable to open URL connexion: " + ex.getMessage());
}
} catch (MalformedURLException ex) {
System.err.println("The URL hasn't been created: " + ex.getMessage());
}
}
return result;
}
It goes thru all that and returns true. Even tho the file is not written.
There are loggers in every catch, but no catch is ever triggered.
When I try to delete a file using ftpclient I am getting reply code as 500. Can someone help me with the issue. As you can see in the commented section of the code I tried to move the file to other folder and I got the reply code as 500 as well.
public boolean sendFile(HttpResponse httpresponse, String accessionNumber)
throws Exception {
FTPClient ftpClient = null;
boolean fileUploadStatus = false;
InputStream inputStream = null;
try {
FTPSClient ftpClient = new FTPSClient(true);
String fileName = "SampletesterFileNine.pdf";
String remotePath = "/";
String tempFile = remotePath + fileName;
try {
ftpClient.connect(server, this.port);
} catch (Exception e) {
e.printstackTrace();
}
int reply = ftpClient.getReplyCode();
logger.info("Reply code connect :" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
boolean login = ftpClient.login(userName, password);
if (login) {
if (ftps) {
((FTPSClient) ftpClient).execPROT("P");
}
logger.info("Logged in to ftp server with host " + server);
} else {
logger.info("login failed");
}
} else {
logger.info("login failed with exception");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
logger.info("Checking whether file exists or not!!");
inputStream = ftpClient.retrieveFileStream(tempFile);
if(inputStream != null) {
logger.info("File already exists");
isFileExist = true;
String toPath = "/failed/SampletesterFileNine.pdf";
/*boolean renamed = ftpClient.rename(tempFile, toPath);
logger.info("replycode is : " + ftpClient.getReplyCode());
if(renamed) {
logger.info("file moved to failed folder successfully");
} else {
logger.info("failed while moving file to failed folder");
} */
boolean renamed = ftpClient.deleteFile(tempFile);
logger.info("replycode is : " + ftpClient.getReplyCode());
if(renamed) {
logger.info("file moved to failed folder successfully");
} else {
logger.info("failed while moving file to failed folder");
}
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
} catch(Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printstackTrace();
}
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
e.printstackTrace();
}
}
return fileUploadStatus;
}
// Trying to upload a file using ftp, file is being uploaded however I am unable to create a directory on my ftp server.
public void uploadFile(){
FTPClient client = new FTPClient();
client.enterLocalPassiveMode();
try {
client.connect(FTP_HOST,21);
client.login(FTP_USER, FTP_PASS);
// If directory is not created
boolean chk=client.changeWorkingDirectory("/files/"+val_spsem+"/"+val_spsubj+"/");
if(!chk)
{ // I am trying to create a directory here
client.makeDirectory("/files/"+val_spsem+"/"+val_spsubj+"/");
client.changeWorkingDirectory("/files/"+val_spsem+"/"+val_spsubj+"/");
}
//Logic ends
File firstLocalFile = new File(path);
InputStream inputStream = new FileInputStream(firstLocalFile);
String firstRemoteFile=file_nm;
client.setFileType(FTPClient.BINARY_FILE_TYPE);
boolean done=client.storeFile(firstRemoteFile,inputStream);
if(done)
{
//Toast.makeText(sub_sem.this,"Upload Completed",Toast.LENGTH_LONG).show();
System.out.println("Upload Completed");
}
} catch (Exception e) {
e.printStackTrace();
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
Did a test,using java to read ftp file,the tools is apache-common-net ftp.I try to read one file,it's ok,but when I read multiple files in a directory,the InputStream(ftpClient.retrieveFileStream) is null.
Can someone help please,thanks.
private static FTPClient ftpClient = new FTPClient();
private static String encoding = System.getProperty("file.encoding");
public static void main(String[] args) {
ftpClient.setControlEncoding(encoding);
try {
ftpClient.connect("host", 21);
ftpClient.login("user", "password");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("connection error!");
System.exit(0);
}
ftpClient.changeWorkingDirectory(new String("/home/neal/test/"
.getBytes(encoding), "iso-8859-1"));
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile f : fs) {
// read all txt file
BufferedReader reader = new BufferedReader(
new InputStreamReader(ftpClient.retrieveFileStream(f.getName())));//the input stream will be null
reader.readLine();
}
ftpClient.logout();//
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The solution that I've used was to create two different connection to the FTP in order to read the data from the two different files.
Code below :
SCFTPClient ftpC = new SCFTPClient("localhost", "admin", "admin",
2222);
String active = ftpC.readFile(file1);
ftpC.disconnect();
SCFTPClient ftpC2 = new SCFTPClient("localhost", "admin", "admin",
2222);
if (null != active) {
file = ftpC2.readFile(file2);
} else {
file = ftpC2.readFile(fileName);
}
ftpC2.disconnect();