This is a continuation of the last thread. I insert 3 files: Two bins (path and a number) and either a jpg or a bmp This does the following.

1: Connects to FTP and changes to C:/ (/)
2: It checks if a webfolder exists. If it is, goes to it. If it isnt, it creates it and goes to it.
3: It checks if a folder with the current date exists. If it exists, it checks if it has more than/equal to 44 files, if it does 3a. If it doesnt, 3b
3a: If 3a, it makes the current date but with a "_2". For example, today the folder would be 20121211 but since it has more than/equal to 44 files, it would be 20121211_2 if it doesnt have more/equal to 44 files, if not continue to 3, 4, etc. It would then change to this folder and continue to 3b
3b: Since it doesnt have less than 44, i go inside the folder. if i am inserting a bmp, i create the bmp inside this folder and then make a new folder with the name being the number and insert the path bin and the number bin. if i am inserting a jpg, i make a new folder with the name being the number, and insert the path bin, the number bin, and the jpg.
4: I then disconect.

The code is big and I dont think Ill translate much. That being said if someone wants me to translate Ill go ahead and do it.

public  void subidaftpfecha(String ip, String usuario, String pass, String fichero, String directorio)
    {
        int counter=1; //Counter so I can add 1, 2, 3, etc to the folder
        FTPFile found; //When I find the correct folder
        int done=0; //When I finish the while

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); //Date format
        Date date = new Date();
        String fechaactual=dateFormat.format(date);
        fechaactual=fechaactual.replace("/",""); //Removing the slashes just in case
        FTPClient client = new FTPClient();

        String extension=fichero.substring(fichero.indexOf("."),fichero.indexOf(".")+4); //Extension

        try 
        {
            if (directorio.equals(""))
            {
                directorio=fechaactual;
            }

            client.connect(ip);
            client.login(usuario,pass);
            client.setFileType(FTP.BINARY_FILE_TYPE);
            String filename = fichero;
            File e=new File(filename);
            FileInputStream s=new FileInputStream(e);
            String cai=fechaactual; //folder I want to use
            client.changeWorkingDirectory("/"); 
            if (client.changeWorkingDirectory("webfolder")==false) //Check if webfolder exists
                {
                    client.makeDirectory("webfolder");
                    client.changeWorkingDirectory("webfolder");
                }
            FTPFile[] list = client.listFiles();
            while (done==0)
            {
                found=null;
                if (counter==1)
                {
                    cai=fechaactual;

                }

                else
                {
                    cai=fechaactual+"_"+Integer.toString(counter); 

                }

                for (int i=0;i<list.length;i++) //I run thru searching for the folder
                {
                    if ((list[i].getType() == FTPFile.DIRECTORY_TYPE) && (list[i].getName().equals(cai)))
                    {
                        found=list[i];
                        break;
                    }
                }


                if (found!=null) //If Ive found the folder Im looking for
                {


                    client.changeWorkingDirectory(found.getName()); //I change to it

                    FTPFile[] list2 = client.listFiles();
                    int archivos=0; //number of files
                    for (int x=0;x<list2.length;x++) //I count the number of files inside of it
                    {
                        if (list2[x].getType()==FTPFile.FILE_TYPE)
                        {
                            archivos=archivos+1;
                        }
                    }

                    //DEBUG
                    System.out.println("Working with "+client.printWorkingDirectory()+"/"+e.getName());
                    System.out.println("Total file: "+archivos);

                    if (archivos<44) //If it is less than 44
                    {
                        if (client.changeWorkingDirectory(directorio)==false) //If It does not exist
                        {
                            client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                            client.setFileType(FTP.BINARY_FILE_TYPE);
                            if (extension.equals(".jpg")) //If Im inserting a JPG, first....
                            {
                                client.storeFile(client.printWorkingDirectory()+"/"+e.getName(), s);
                                return;
                            }
                            client.makeDirectory(directorio);
                            client.changeWorkingDirectory(directorio);
                            client.storeFile(client.printWorkingDirectory()+"/"+e.getName(), s);
                            done=1;
                        }

                    }
                    else //If it exists
                    {
                        client.changeToParentDirectory();
                        //f.changeWorkingDirectory("/webfolder/");
                        counter=counter+1;
                    }


                }//end if found not null

                else //if found equals null
                {

                    client.makeDirectory(cai);
                    client.changeWorkingDirectory(cai);


                    if (client.changeWorkingDirectory(directorio)==false)
                    {
                        client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                        client.setFileType(FTP.BINARY_FILE_TYPE);
                        if (extension.equals(".jpg"))
                        {
                            client.storeFile(client.printWorkingDirectory()+"/"+e.getName(), s);
                            return;
                        }
                        client.makeDirectory(directorio);
                        client.changeWorkingDirectory(directorio);
                        client.storeFile(client.printWorkingDirectory()+"/"+e.getName(), s);
                        done=1;
                    }



                }


            } //end while


        } //end try
        catch (SocketException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            try 
            {


                if (client.isConnected()==true)
                {
                    client.logout();
                    client.disconnect();
                }
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

As you can see this has parameters. First three are simple FTP auth. The variable "fichero" is the file I am inserting (this can be one of the two bins (I call this function at least three times, one more path bin, another for the number bin and another for the jpg or bmp. I have to do these three connections so please bear this in mind)). The variable "directory" is the name of the folder I am inserting this files. Lets keep something in mind: The JPG are not in the actual "directory" I am pointing (reason why the directory can by semioptional). Thats why the JPG has a return because as soon as I insert it, I have no reason to keep going.

Basically I dont know if this is going to work so I need some input on how it looks :)

Thank you very much.

I'm not looking at how it works, but I will give you some thought about what may happens..

1)Line 13, do you know that a file name can contain most character (if not all)? For example, you could have a file name "abcd.efg.doc" especially on Windows. The way you extracting a file extension may give you an unexpected result. What you should do is to find the last index of the full stop '.' using lastIndexOf() instead.
2)Line 17, it could throw a NPE (NullPointerException) if your directorio is null. Then you do not have a proper catch clause to handle it and that may cause an unexpected behavior later on.
3)Lines 87 and 120, do you also know that the file extension is case-sensitive on Linux/Unix? I'm not sure about Mac though because I don't have one to work with yet (thinking about buying one). For example, apic.JPG is not equal to apic.jpg. If you are testing the extension without ignoring case, I assume you expect the kind of result I mentioned above (case-sensitive).

Just my two cents...

I'm not looking at how it works, but I will give you some thought about what may happens.. 1)Line 13, do you know that a file name can contain most character (if not all)? For example, you could have a file name "abcd.efg.doc" especially on Windows. The way you extracting a file extension may give you an unexpected result. What you should do is to find the last index of the full stop '.' using lastIndexOf() instead.
2)Line 17, it could throw a NPE (NullPointerException) if your directorio is null. Then you do not have a proper catch clause to handle it and that may cause an unexpected behavior later on.
3)Lines 87 and 120, do you also know that the file extension is case-sensitive on Linux/Unix? I'm not sure about Mac though because I don't have one to work with yet (thinking about buying one). For example, apic.JPG is not equal to apic.jpg. If you are testing the extension without ignoring case, I assume you expect the kind of result I mentioned above (case-sensitive). Just my two cents...

I'm not looking at how it works, but I will give you some thought about what may happens.. 1)Line 13, do you know that a file name can contain most character (if not all)? For example, you could have a file name "abcd.efg.doc" especially on Windows. The way you extracting a file extension may give you an unexpected result. What you should do is to find the last index of the full stop '.' using lastIndexOf() instead.
2)Line 17, it could throw a NPE (NullPointerException) if your directorio is null. Then you do not have a proper catch clause to handle it and that may cause an unexpected behavior later on.
3)Lines 87 and 120, do you also know that the file extension is case-sensitive on Linux/Unix? I'm not sure about Mac though because I don't have one to work with yet (thinking about buying one). For example, apic.JPG is not equal to apic.jpg. If you are testing the extension without ignoring case, I assume you expect the kind of result I mentioned above (case-sensitive). Just my two cents...

(Posting on Daniweb is crap so sorry for that quote. Blame Daniweb, not me)

1) The filenames and directory names are controlled by me. There are only 2 possible names. Path1.bin and date/time in miliseconds (such as 1352739317). The strings are hardcoded by me, they arent dynamic (miliseconds obviously not but its just that numbers) It isnt something user inserted or anything

2) See (1) but even so, its better to be safe than sorry. Changed to:

if (directorio.equals("") || directorio==null)
            {
                directorio=fechaactual;
            }

Thank you :)

3) See (2) . Changed to:

String extension=fichero.substring(fichero.indexOf("."),fichero.indexOf(".")+4).toLowerCase();

Just in case :) Thanks

Also, this function is called and returns a void. Im thinking of changed it to returning a int. This way I can control if it has made the webfolder (returning a say 1), if it has made a folder with miliseconds (return 2) if it has inserted the path1 (a 3) if it has inserted the bin with mliiseconds (return 4) or if it has inserted a jpg (5) or a bmp (6) or if it has a error (-1). This allows me to reuse the function in different ways and correctly with different ifs in the main code. Do you think this is a good idea?

Thank you!

Rather than use an int return (hard to understand, easy to confuse) use a simple enum, eg
enum FolderAction{INSERTED_PATH, INSERTED_MSECS, .... ,ERROR;}
guaranteed safe, and self-documenting

Just to get more information and with this more help, this is the main program (originalcode):

if (writejpg==1)
                                        {
                                            ftp.subidaftp(ip, "Anonymous", "pass", nombreprograma+".bmp", "/PROGRAMAS1_W/");
                                        }
                                        else
                                        {
                                            ftp.subidaftp(ip, "Anonymous", "pass", nombreprograma+".jpg", "/PROGRAMAS1_W/"+nombreprograma+"/");
                                        }

                                        ftp.hacercarpetaftp(ip, "Anonymous", "pass", nombreprograma);
                                        ftp.subidaftp(ip, "Anonymous", "pass", nombreprograma+".bin", "/PROGRAMAS1_W/"+nombreprograma+"/");
                                        ftp.subidaftp(ip, "Anonymous", "pass", "Path1.bin", "/PROGRAMAS1_W/"+nombreprograma+"/");   

Those functions "hacercarpetaftp" and "subidaftp" are these:

hacercarpetaftp:

public  void hacercarpetaftp(String ip, String usuario, String pass, String carpeta)
    {

        FTPClient client = new FTPClient();
        try 
        {

            client.connect(ip);
            client.login(usuario, pass);

            //String dir=client.printWorkingDirectory();
            boolean existe=client.changeWorkingDirectory(carpeta);
            if (existe==false)
            {
                client.makeDirectory("/PROGRAMAS1_W/"+carpeta);
                //client.changeWorkingDirectory("/PROGRAMAS1_W/");
                client.logout();
            }

        } 
        catch (SocketException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            try 
            {

                client.disconnect();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

subidaftp

subidaftp(String ip, String usuario, String pass, String fichero, String directorio)
    {

        FTPClient client = new FTPClient();
        FileInputStream fis = null;
        try 
        {
            client.connect(ip);
            client.login(usuario, pass);
            try 
            {
                client.setFileType(FTP.BINARY_FILE_TYPE);
            } 
            catch (IOException e1) 
            {
                System.out.println("ERROR: No se ha podido cambiar el fichero a tipo binario ( " +e1.getLocalizedMessage()+" )");
            }
            String filename = fichero;
            fis = new FileInputStream(filename);    

            boolean existe=client.changeWorkingDirectory(directorio);
            if (existe==false)
            {
                client.makeDirectory(directorio);
                client.storeFile(filename, fis);
                client.rename(filename, directorio + filename);
            }
            else
            {
                client.storeFile(filename, fis);
                client.rename(filename, directorio + filename);
            }
            client.logout();

        } 
        catch (IOException e) 
        {
            if (e.getLocalizedMessage().equals("Connection refused")==true)
            {
                System.out.println("La maquina a la que me he intentado conectar, me ha rechazado la conexion. Su IP es " + ip + " Revisa su configuracion y permisos.");
            }
            else
            {
                System.out.println("ERROR: Ha ocurrido un error ( " +e.getLocalizedMessage()+" )");
            }


        }
        finally
        {
            try
            {
                if (fis!=null)
                {
                    fis.close();
                }
                //25-09-2012 CAMBIO Compruebo si esta conectado o no el cliente FTP
                if (client.isConnected()==true)
                {
                    client.disconnect();
                }

            }
            catch (IOException e) 
            {
                System.out.println("ERROR: Ha ocurrido un error al cerrar el fichero ( " +e.getLocalizedMessage()+" )");
            }
        }
    }public  void hacercarpetaftp(String ip, String usuario, String pass, String carpeta)
    {

        FTPClient client = new FTPClient();
        try 
        {

            client.connect(ip);
            client.login(usuario, pass);

            //String dir=client.printWorkingDirectory();
            boolean existe=client.changeWorkingDirectory(carpeta);
            if (existe==false)
            {
                client.makeDirectory("/PROGRAMAS1_W/"+carpeta);
                //client.changeWorkingDirectory("/PROGRAMAS1_W/");
                client.logout();
            }

        } 
        catch (SocketException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            try 
            {

                client.disconnect();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Hope this helps :)

It looks good then?

What do I call in my main program when calling this function? What paramaters should I pass?

I believe I should pass the main file and the directory its going to. Am I right?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.