setPermission in java ftp - java

I am trying to create a directory on FTP server and upload a file in that directory. The Directory is created successfully but file is not uploaded may be due to write permission
FTPClient ftpClient = new FTPClient();
public void ftpConnection(){
try {
ftpClient.connect(server,port);
ftpClient.enterLocalPassiveMode();
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
}
boolean success = ftpClient.login(user, pass);
if (!success) {
System.out.println("Could not login to the server");
} else {
System.out.println("LOGGED IN SERVER");
boolean created = ftpClient.makeDirectory("/usr/prtsim");
int returnCode = ftpClient.getReplyCode();
System.out.println(returnCode);
if(created){
System.out.println("created");
ftpClient.changeWorkingDirectory("/usr/prtsim");
uploadFile();
}
else{
if (returnCode == 550)
System.out.println("Directory already present");
else
System.out.println("not created");
}
ftpClient.logout();
ftpClient.disconnect();
}
}
catch(IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
public void uploadFile() throws FileNotFoundException, IOException{
File firstLocalFile = new File("C:\\Users\\sswaroo\\Desktop\\sampletext.txt");
//ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String firstRemoteFile = "sampletext.txt";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("The first file is uploaded successfully.");
}
}
}
I am getting following response:
LOGGED IN SERVER
257
created
Start uploading first file
The first file is uploaded successfully.
Could you please help me in setting the write permission on directory I created?

Based on your output it looks like you never reach the line
System.out.println("Start uploading first file");
The call
new FileInputStream(firstLocalFile)
will throw a FileNotFoundException if the file passed to it cannot be accessed.
I'd suggest checking to see if the file created at the start of your method is correct and accessible.

Related

Uploading a file in a specific path of an FTP server [duplicate]

This question already has answers here:
FtpClient storeFile always return False
(5 answers)
Closed 8 years ago.
I want to upload a file in a specific path in an ftp server the code is quite simple:
public static void main(String[] args) {
String server = "xx.xx.xx.xx";
String user = "xxx";
String pass = "xxx";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server);
System.out.println("Connected to " + server + ".");
System.out.print(ftpClient.getReplyString());
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// uploads first file using an InputStream
File firstLocalFile = new File("/tmp/PAR.TXT");
String firstRemoteFile = "/DATA/OUTFILES/PAR.TXT";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
System.out.println("done:"+done);
inputStream.close();
if (done) {
System.out.println("The file is uploaded successfully.");
}
} 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();
}
}
}
I always get done = false.
Here's the result:
Connected to xx.xx.xx.xx.
220 "Welcome (logging activated)"
Start uploading file
done:false
I printed the FtpClient#getReplyCode(). and i get this:
500 Illegal PORT command.
You can only access files relative to the root folder of the ftp server. You need to configure your ftp server to add a virtual folder pointing to the path you want.
I passed to PassiveMode and it works now

Unable to download files from FTP server

I've created Java function that downloads files from FTP server. It works fine from my local machine. But I need to run it under linux server (means another host and port). And the function gives an error
The collection, array, map, iterator, or enumeration portion of a for statement cannot be null
Caused in a line with the code:
for(String f : ftpNames) {
ftpclient.retrieveFile(f, os); // os is OutputStream
}
So it doesn't see the files...
I added
ftpclient.enterRemotePassiveMode();
And ftpclient.getPassiveHost() returns 227 Entering Passive Mode (x,x,x,x,204,15)
Tried to list and download them via shell - it works.
How should I modify my code to solve the problem? Thanks.
UPD. I got log from FTP server I'm trying to get files from, and there is such string:
425 Cannot open data connection
Full code:
static boolean ftpFilesDownload(String ip, int port, String login, String passwd, String ftpdir, String localdir) throws IOException {
Boolean result = false;
FTPClient client = new FTPClient();
String separator = File.separator;
try {
client.connect(ip, port);
System.out.println(client.getReplyString());
client.login(login, passwd);
System.out.println(client.getReplyString());
client.setControlKeepAliveTimeout(1000*60*5);
client.setControlKeepAliveReplyTimeout(1000*60*5);
client.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("client setFileType success");
client.changeWorkingDirectory(ftpdir);
System.out.println(client.getReplyString());
client.printWorkingDirectory();
System.out.println("directory changed");
FTPFile[] ftpFiles = client.listFiles();
System.out.println(ftpFiles);
String[] ftpNames = client.listNames();
System.out.println("the files are " + Arrays.toString(ftpNames)); // so null here...
for(String f : ftpNames) {
String localfile = localdir + f;
OutputStream os = new FileOutputStream(localfile);
try {
result = client.retrieveFile(f, os);
System.out.println("DOWNLOADING STARTED);
System.out.println(client.getReplyString());
client.noop();
}
catch(Exception e) {
System.out.println(e);
result = false;
}
finally {
if(os != null)
os.close();
}
}
client.logout();
System.out.println(client.getReplyString());
}
catch(Exception e)
{
System.out.println(e);
result = false;
}
finally
{
try
{
client.disconnect();
}
catch(Exception e)
{
System.out.println(e);
result = false;
}
}
return result;
}
As the error message explains, you're trying to iterate over a null object. You should check for this (or make sure an empty Iterable is used perhaps)
If this is an execptional (error) state, I'd check for this explicitly and throw some kind of runtime exception, e.g.:
if (ftpNames == null) {
throw new IllegalArgumentException("Cannot use a null set of FTP servers");
}
for (String f : ftpNames) {
ftpclient.retrieveFile(f, os); // os is OutputStream
}
Alternatively you could try to continue with no FTP servers, but seems a bit pointless.
Try to use ftpclient.enterLocalActiveMode();

FTP File upload using Java

hey i want to upload a file to a directory called 'screenshots' on my webserver via FTP using java. I have been using this code and it says that it stores the file successfully and connected successfully but when i check my screenshots directory via the cpanel i dont see the file that was uploaded any help?
public static void uploadFilee() {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("****************");
client.login("********", "********");
System.out.println("Connected Successfully");
String filename = "C:/Users/Christian/Desktop/screenshots/img_" + queueInfo.get("SessionID");
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
System.out.println("Stored File Successfully");
client.logout();
} catch (IOException e) {
System.out.println("Error_1");
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
System.out.println("Error_2");
e.printStackTrace();
}
}
}
`
You may want to review this page
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#_storeFile(java.lang.String,java.lang.String,java.io.InputStream)
you have your statements such as storefile in a try statement, but if they fail, they return false, not an exception.
changing your code to inspect the return values of each function should help you find where your problem lies.

apache.commons.net.ftp.FTPClient not uploading the file to the required folder

I'm using the following code to upload an xml file to the directory /home/domainname/public_html/guest in the server. However, the file is uploaded only to the location /home/domainname. It is not uploading to the child directories. Please advise.
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(Util.getProductsXMLFTPServer());
client.login(Util.getProductsXMLFTPUser(), Util.getProductsXMLFTPPassword());
//
// Create an InputStream of the file to be uploaded
//
fis = new FileInputStream(new File(Util.getProductsXMLFTPInputFilePath(), Util.getProductsXMLFTPOutputFileName()));
client.changeWorkingDirectory(Util.getProductsXMLFTPUploadPath());
client.storeFile(Util.getProductsXMLFTPOutputFileName(), fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
I checked your code, it works. I've only changed file type declaration to binary, which may be not needed for XML files.
Here's my complete code for reference:
package apachenet.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class App {
public static void main( String[] args ) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(/*Util.getProductsXMLFTPServer()*/"127.0.0.1");
client.login(/*Util.getProductsXMLFTPUser()*/"pwyrwinski",
/*Util.getProductsXMLFTPPassword()*/"secret");
client.setFileType(FTP.BINARY_FILE_TYPE); // optional
fis = new FileInputStream(
new File(/* Util.getProductsXMLFTPInputFilePath() */"/home/pwyrwinski",
/* Util.getProductsXMLFTPOutputFileName() */"img.png"));
client.changeWorkingDirectory(/*Util.getProductsXMLFTPUploadPath()*/ "someDir");
client.storeFile(/*Util.getProductsXMLFTPOutputFileName()*/"img_bis.png", fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As you can see it's roughly the same as yours.
Util class calls are replaced with raw data.
When I ran it, file /home/pwyrwinski/img.png was uploaded to {FTP_USER_ROOT}/someDir directory on ftp server with name changed to img_bis.png. I assume this is exactly what you wanted to achieve.
Let's go back to your problem.
Try to check what is returned from
Util.getProductsXMLFTPUploadPath() call. My guess is it's not what
you're expecting - so debug it in your IDE or print it to the console.
Check if path returned from Util.getProductsXMLFTPUploadPath()
call starts with slash, it shouldn't.
UPDATE 1.
Does direcory /home/domainname/public_html/guest exist on server?
Add following method to your class:
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);
}
}
}
and call it after every ftp-client's method call. This will give you codes and descriptions of every command result. I suspect client.changeWorkingDirectory(...) ends with error, probably: 550 Permission Denied (or No such file or folder).
Next modification will be:
client.login(Util.getProductsXMLFTPUser(), Util.getProductsXMLFTPPassword());
System.out.println(client.printWorkingDirectory()); // added this line!
this will tell us what is current working directory after login in.
Please post your results.
FTPClient ftpClient = new FTPClient();
try {
System.out.println("before server connection");
ftpClient.connect(server, port);
System.out.println("before user name and passwod");
ftpClient.login(user, pass);
ftpClient.enterLocalActiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("connection sucess");
// windows working fine
File secondLocalFile = new File("/home/aims/archived_reports/tes_S_000000123/test.pdf");
// String secondRemoteFile = "/archived_reports/PermanentRecord.pdf";
//linux
// File secondLocalFile = new File("/archived_reports/tes_S_000009123/test.pdf");
String secondRemoteFile = "remotefilename.pdf";
InputStream inputStream = new FileInputStream(secondLocalFile);
System.out.println("Start uploading second file");
ftpClient.changeWorkingDirectory("/reports");// home/ftp.test/reports folder
System.out.println("Prasent Working Directory :"+ftpClient.printWorkingDirectory());
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
int returnCode = ftpClient.getReplyCode();
System.out.println(returnCode);
byte[] bytesIn = new byte[4096];
int read = 1;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
System.out.println();
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
System.out.println("The second file is uploaded successfully.");
}

File is copied on the FTP server not moved in java

Using below program i am able to upload zip file on ftp server.
But it makes the copy of the zip file and upload the file on ftp server.
I want it should delete the file from local system and copy it to server i.e. it should move the file not copy.Please guide
public class UploadFile {
public static void main(String args[])
{
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect("ipadddress");
ftp.login("abc", "abc");
reply = ftp.getReplyCode();
System.out.println("reply1" + reply);
if(!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
}
System.out.println("FTP server connected.");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
InputStream input= new FileInputStream("D:\\testencrypted.zip");
String dirTree="/Vel";
boolean dirExists = true;
String[] directories = dirTree.split("/");
for (String dir : directories )
{
if (!dir.isEmpty() )
{
if (dirExists)
{
dirExists = ftp.changeWorkingDirectory(dir);
}
else if (!dirExists)
{
System.out.println("dir tree" + ftp.printWorkingDirectory());
if (!ftp.makeDirectory(dir))
{
throw new IOException("Unable to create remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'");
}
if (!ftp.changeWorkingDirectory(dir))
{
throw new IOException("Unable to change into newly created remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'");
}
System.out.println("dir tree" + ftp.printWorkingDirectory());
}
}
}
ftp.storeFile(dirTree+"/t1.zip",input);
input.close();
ftp.logout();
}
catch(Exception e)
{
System.out.println("err"+ e);
}
finally
{
if(ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch(Exception ioe)
{
}
}
}
}
}
So, once you've completed the upload (and you're sure that it was sucessful, simply use File.delete() to remove the file from the local disk.
File sourceFile = new File("D:\\testencrypted.zip");
InputStream input= new FileInputStream(sourceFile);
// Upload the file...
// Make sure you close the input stream first ;)
if (!sourceFile.delete()) {
System.out.println("Failed to delete " + sourceFile + " from local disk");
sourceFile.deleteOnExit(); // try and delete on JVM exit...
}

Categories