Reputation: 2628
Below code uploads file on the FTP server
public class UploadFile {
static ResourceBundle rsBundle = ResourceBundle.getBundle("com.mindcraft.resources.resources");
public void upload(String host,String username,String pwd,String inputfile,String uploadpath,String zip_filename)
{
//String zip_file_name= rsBundle.getString("zip_filename");
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect(host);
ftp.login(username, pwd);
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(inputfile);
System.out.println("Directory.." + ftp.printWorkingDirectory());
String dirTree=uploadpath;
boolean dirExists = true;
String[] directories = dirTree.split("/");
for (String dir : directories )
{
if (!dir.isEmpty() )
{
if (dirExists)
{
dirExists = ftp.changeWorkingDirectory(dir);
ftp.storeFile(dirTree+zip_filename,input);
System.out.println("1..");
}
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+zip_filename,input);
}
}
}
System.out.println( ftp.getReplyString() );
input.close();
ftp.logout();
}
catch(Exception e)
{
System.out.println("err"+ e);
e.printStackTrace();
}
finally
{
if(ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch(Exception ioe)
{
}
}
}
}
}
It works fine when the upload path has one folder eg. /folder1/
But It uploads blank file of byte 0 when there is subfolder or more than one directory eg. /folder1/folder2/
What can be the issue??
Upvotes: 1
Views: 599
Reputation: 15261
Joop Eggen got the point, I would just like to add that if you want to retrieve files/directories, it is a good practice to write:
String[] directories = dirTree.split(File.separator);
instead of
String[] directories = dirTree.split("/");
because it will make your code more portable. FTP server doesn't always need to stay on Unix/Linux.
Upvotes: 1
Reputation: 109613
ftp.storeFile(dirTree+zip_filename,input);
should be called after the for
creating all subdirectories, and going to the correct directory.
BTW could have helped introducing a function makeAndGoToDirectory.
Upvotes: 1