FTP progarm using JAVA

I need to fetch the files from Linux server through ftp using java. I am using the following package.
org.apache.commons.net.ftp.*
FTPClient class has the features like makeDirctory ,disconnect and so on.
But, FTPClient class can not be recognizable. How can I make this cass as recognizable?

Cross-post
http://forum.java.sun.com/thread.jspa?threadID=639588&tstart=0

Similar Messages

  • Ftp connection using java

    Hi All,
    I need to upload a file through ftp connection uisng java calss. any one know please reply me
    Thanks
    K.Kalikumar

    Hi Kali,
    I have worked on similar issues sending you the code.. hope it should work. I had written a TelnetInterface class where I did all operation inside the constructor.
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.InputStream;
    import java.io.PrintStream;
    import org.apache.commons.net.telnet.TelnetClient;
    public class TelnetInterface {
         private TelnetClient telnet = new TelnetClient();
         private InputStream in;
         private PrintStream out;
         private String prompt = ">";
         private boolean isConnected ;
    public TelnetInterface(){
         public TelnetInterface(HttpServletRequest request) {
                   HttpSession session = request.getSession();
                   PropertyReader propReader = (PropertyReader)session.getAttribute("propReader");
                   String host=null,user=null,password=null,port=null;
                   int unixPort= 0;
    //                Get Unix credentials
                   if(propReader != null){
                        host=(String)propReader.getProperty("UNIX_HOST");
                        user=(String)propReader.getProperty("UNIX_UNAME");
                        password=(String)propReader.getProperty("UNIX_PWD");
                        port=(String)propReader.getProperty("UNIX_PORT");
                        unixPort = Integer.parseInt(port) ;
    //                    Connect to the specified server
                   System.out.println("Inside telnet Interface");
                   try{
                        telnet.connect(host, unixPort);
                        isConnected = true;
                        in = telnet.getInputStream();
                        out = new PrintStream(telnet.getOutputStream());
    //                    Log the user on
                        readUntil("login: ");
                        write(user);
                        System.out.println("user:"+ user);
                        readUntil("Password: ");
                        write(password);
                        System.out.println("password:"+ password);
                        sendCommand("su - loginuser");
                        su(" password");
                   }catch (IOException e) {
                        e.printStackTrace();
                        isConnected = false;     
                   }catch (Exception e){
                        e.printStackTrace();
         }

  • FTP downloading using Java

    Hi,
    My program wants the capability to download a zipped file to a client machine for offline viewing. The zipping can be done using the util.zip package. But to place the file physically on to the client machine, can I use FTP?
    I know one of the options is to place the zip file somewhere in the web server and give a link from where the client can download it. But, is it possible to write the zip file physically to the client's machine?
    TIA
    manoj.

    You can use FTP to accomplish this. There are a set of classes (open source) available to do this. Check out the following site for download and API information.
    http://www.savarese.org/oro/index.html. This is the same package used by Jakarta Ant for the external FTP task.
    Hi,
    My program wants the capability to download a zipped
    file to a client machine for offline viewing. The
    zipping can be done using the util.zip package. But
    to place the file physically on to the client machine,
    can I use FTP?
    I know one of the options is to place the zip file
    somewhere in the web server and give a link from where
    the client can download it. But, is it possible to
    write the zip file physically to the client's
    machine?
    TIA
    manoj.

  • Use java code to start  ftp server in Windows

    I am writing an application using java to start the FTP server on Windows system Could anybody give me an idea on how to start?

    http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/developer/onlineTraining/Programmin
    /BasicJava1/compile.html
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's
    Thinkin
    in Java
    Joshua Bloch's
    [url=http://www.amazon.co.uk/exec/obidos/Author=Bloch,%
    0Josh]Effective Java
    Bert Bates and Kathy Sierra's
    [url=http://www.amazon.com/exec/obidos/tg/detail/-/0596
    04656?v=glance]Head First Java
    lol. That's one way to start.
    But really, why would you want to start an ftp server from java?? You should use the right tool for whatever job you need to accomplish and you can set up windows to automatically start the server when it boots.
    majinda might say: it si lkie thrownig chickne at palm to knock datse to ground. bettre to let donkey kick tree.
    But if you insist, you'll probably need JNI.

  • FTP using java API

    i saw the ftp upload an download codes in one of the previous forums...
    is it possible for a directory listing of the remote system i.e., the user can select the files which he has to download from the server . is it possible to do that using java api without any third party package???

    Type java ftp to google and you'll find a couple of dozen Java FTP client implementations.
    One of them comes with Sun's JDK, sun.net.ftp.FtpClient. It's in the "sun" package hierarchy, which means it's unsupported, undocumented and subject to change without notice.
    What I've done myself is grab Sun's FtpClient and copy it to one of my own packages; that way it won't suddenly change. (I did that when it had a couple of dodgy changes between using active/passive/extended passive modes.)

  • Ftp using java... urgent!!!!

    im student
    i did a program....but it doesn't work....i dont know what is the problem....please..i hope that someone can helpme and correct my mistake....
    thank you so much!!!!!
    import sun.net.*;
    import java.net.*;
    import sun.net.ftp.*;
    import java.io.*;
    import sun.net.TelnetInputStream;
    class FtpClientes{
         public static void main(String args[]){
              try{
              int ch;
    byte[] buffer = new byte[4096];
    int bytes_read;
              System.out.println("comienza el ftp");
              FtpClient ftp=new FtpClient();
    ftp.openServer("ftp.eafit.edu.co");
    ftp.login("myname","mypassword");
              System.out.println("buscando directorio.....");
    TelnetInputStream lista =ftp.list();
    System.out.println("buscando directorio.....");
    while( (ch = lista.read()) != -1 )
    System.out.print((char)ch);
    ftp.cd("EAFIT/encuesta_planeacion/encuesta_final.doc");
    System.out.println("buscando directorio.....");
    ftp.binary();
              System.out.println("cogiendo archivo.....");
    TelnetInputStream in = ftp.get("/EAFIT/encuesta_planeacion/encuesta_final.doc");
              System.out.println("leyendo el archivo.....");
              BufferedReader d = new BufferedReader(new InputStreamReader(in));
              while(d.readLine().length()>0){
                   System.out.println(d.readLine());
              System.out.println("preparados para copiar el archivo.....");
    FileInputStream fis = new FileInputStream("/EAFIT/encuesta_planeacion/encuesta_final.doc" );
    TelnetOutputStream ts = ftp.put("/EAFIT/encuesta_planeacion/encuesta_final.doc");
              System.out.println("copiando el archivo.....");
              while( (fis.read(buffer)) != -1 ) {
                   ts.write(buffer);
    System.out.println("cerrando todo lo que alguna vez abri.....");
              ts.close();
              fis.close();
         ftp.closeServer();
         }catch(Exception e){}

    Hi BatemanA,
    Can you please clarify more? I have not used FTP so much so I don't know how to "upload" a file using this FTP URL.
    Thank you.
    Maulin
    The ftp protocol handlers supports uploading and
    download ing aswell as directory and other ftp
    operations that can be encoded in the URL (see RFC
    1738).

  • Process TIFF file from FTP server using File/FTP adapter

    Hi,
    I have a requirement to process a scanned document TIFF file from a directory on an FTP server using the File/FTP adapter and process through XI into a Web Service via a receiver SOAP adapter.
    My question is can the file/FTP adapter be used to process the TIFF file into XI from an FTP server ? Also, what settings need to be made on the file adapter to allow this file to be processed into XI ?
    Thanks in advance
    Colin

    hi colin,
    TIFF is type of image file, it can be converted to binary using java mapping
    refer this pdf
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/10dd67dd-a42b-2a10-2785-91c40ee56c0b
    regards
    Ramesh P

  • Need Help to locate a file on a FTP server using MediaLocator class

    Hi Friends,
    This is Venkat. Iam currently working on a Multimedia J2EE web project. Iam working on a requirement to
    show Thumbnail view for uploaded media. For this i have downloaded a standalone code from the following site.
    http://www.exactfutures.com/index02.htm.
    This code converts frames of a media files to jpg images which i can use them to show as Thumbnails.
    The code takes file name which is present in project folder as parameter. But in my web project iam using a FTP server to store my media files.
    The above code uses Java Media Framework along with another API Fobs4JMF. The media file name is passed to MediaLocator class constructor which is located in the project folder. Iam talking about a standalone application here.
    But my project is a J2EE web application.
    Now my problem is that, how can i refer a file which is located on a external FTP server and pass it to MediaLocator or some other class.
    Say the ftp file URL is mms://wm.testuser.net/12365741/testvideo.wmv
    Guys hope you are clear abt my problem. Please help me ASAP.
    Below is the part of code
         * Constructor
         public vid2jpg(String path) {
              MediaLocator ml;
              String args = path;
              if ((ml = new MediaLocator(args)) == null) {
                   System.out.println("Cannot build media locator from: " + args);
              if (!open(ml)) {
                   System.out.println("Failed to open media source");
         * Given a MediaLocator, create a processor and start
         private boolean open(MediaLocator ml) {
              System.out.println("Create processor for: " + ml);
              try {
                   p = Manager.createProcessor(ml);
              } catch (Exception e) {
                   System.out.println("Failed to create a processor from the given media source: " + e);
                   return false;
              p.addControllerListener(this);
              // Put the Processor into configured state.
              p.configure();
              if (!waitForState(p.Configured)) {
                   System.out.println("Failed to configure the processor.");
                   return false;
              // Get the raw output from the Processor.
              p.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW));
    Thanks in Advance for your time.
    Venkat
    Edited by: VenkataGuru on Jul 23, 2008 5:30 PM

    Hi Mani,
    Below is code that ran successfully on a cRIO-9002.  It looks much the same as yours, please double-check the formatting of your string controls.  If things still do not work, let's look at the cRIO more closely.
    Message Edited by Pie56694 on 06-30-2008 09:45 AM
    Attachments:
    FTPDELE3.jpg ‏28 KB
    FTPDELE.jpg ‏24 KB
    FTPDELE2.jpg ‏18 KB

  • How to get  current working directory of the ftp server,in java application

    Hi All,
    I?m FTP?ing the file using java.net.url.
    Here is the snippet of the code:
    public void ftpFile()throws ChrsException
    try
    System.out.println("FTPing the file '"+localfile+"'");
    OutputStream os = openUploadStream(targetfile);
    FileInputStream is = new FileInputStream(localfile);
    byte[] buf = new byte[16384];
    int noOfBytesRead;
    while (true)
    //Read the data from the source File into buf
    noOfBytesRead = is.read(buf);
    if (noOfBytesRead <= 0)
    break;
    //Writes the data present in the buf to the target file
    os.write(buf, 0, noOfBytesRead);
    os.close();
    is.close();
    close();
    System.out.println ("The file '"+localfile+"' is Sucessfully FTP'd to '"+targetfile+"'");
    catch (MalformedURLException malExcp)
    System.out.println ("Invalid URL. Error in FTP'ing the file: \""+localfile+"\"");
    catch(IOException ioe)
    System.out.println ("Error in FTP'ing the file: \""+localfile+"\"");
    private OutputStream openUploadStream(String targetfile) throws MalformedURLException, IOException
    URL url = null;
    //Creates a URL object with FTP protocol
    if (user == null)
    url = new URL("ftp://" + host + "/" + targetfile + ";type=i");
    else
    url = new URL("ftp://" + user + ":" + password + "@" + host + "/" + targetfile + ";type=i");
    urlc = url.openConnection();
    //Get the OutputStream that writes to this connection.
    OutputStream os = urlc.getOutputStream();
    return os;
    Now I need to find what the current directory is when the user logs in with username and password on to the FTP server in java.
    Thanks in Advance.

    as soon as user logs in he is taken to the directory
    "ftproot/pub/abc".
    now If I execute pwd command , is hould be able to
    get to know tht user is under "ftproot/pub/abc"Three respected posters, well two plus me ;-), have just told you otherwise. The information about the current directory is (a) secure and (b) useless to the user, as he can't do anything with it. The user doesn't want to know that at all and you shouldn't try to tell him. And in any case FTP doesn't support it, again for security reasons, so you can't do it.
    Just accept it.

  • Access mirror site using java, download files and other information?

    Hi, I have 2 nodes/servers on the system both running webservers and having the same interface, but at a time user will access one node at a time from their browser, but this interface will be able to allow the user to get information from the both the nodes. the information that the user can get is DB stored as well as files on the disk of either node.
    i can manage the DB, cuz there is nothing to it, but how do I get files from the other node?
    currently any files/web documents are all stored in a application directory of the web root and protected by htaccess i believe, so when a user logs on to node one he can access all plain text/binary files along with web content since the web server authorizes the user to access anything in that dir. but at the same time from the same session I want to be able to access files in a mirror site using the same username and password and not having him to enter it again. the username/pass combo is replicated on both the servers, it this possible?
    currently i use the http password protection provided by apache to access one node, but can i use the same session on another machine with the same credentials?
    If this is not possible how can i do this programatically using java? can i do can "ls" on the directory i want on another server and display the list to the user and then when he clicks on that file name i fetch it from the backup/mirror server and have him save it using http or ftp?
    It would be great if we can get a solution to this.
    Thank you very much in advance.
    Ankur

    If you install the web server on different machines, It is possible to share the informations between them.

  • How to access a file in Unix server from windows using java

    I want to access a file in unix server from windows using java program.
    I have the following code. I am able to open the url in a web browser.
    String urlStr="ftp:user:passwd@unix-server:ftp-port//javatest/test.csv;type=i";
    URL url = new URL(urlStr);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream)));
    String inputLine;
    while((inputLine=in.readLine()))!=null){
    System.out.println(inputLine);
    in.close();
    I get the following error
    java.io.FileNotFoundException: /javatest/test.csv
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:333)
    at java.net.URL.openStream(URL.java:960)
    at com.test.samples.Test.main(Test.java:45)

    urlStr="ftp:user:passwd@unix-server:ftp-port//javatest/test.csv;type=i";
    I have given the format of the urlStr that I am using in the code. The actiual values are used in my code. I have tried pasting this url in the browser and it opens the file.

  • Archiving File on Shared Folder in Linux using java code

    Hi All,
    I have a requirement wherein I have to ftp a file (Feed.txt) from windows FTP server to Linux machine1 and archive the same file (with timestamp suffixed on file name like Feed.txt_22April) on Linux Machine2. I am
    trying to achieve this through java code. I am able to ftp the file(Feed.txt) from windows ftp server to Linux machine1 /opt/ftproot directory and archiving the same file under /opt/ftproot/archive directory of Linux
    Machine1 with timestamp suffixed on file name.
    My archiving requirement is still not achieved. So, for that I created a shared folder “/temp/shared” on Linux Machine2 and mounted the /temp/shared folder of Linux Machine2 on /opt/ftproot/archive folder of
    Linux Machine1 using following command:
    # mount LinuxMachine2: /temp/shared /opt/ftproot/archive
    Note: I have given full permission on both the folders.
    Logically, archiving the Feed.txt with timestamp in it name under /opt/ftproot/archive folder should create the file in /temp/shared folder of Linux Machine2. But instead of archiving the file on
    /opt/ftproot/archive folder, it archive the file on /opt/ftproot folder.
    In my java code, I have specified copyDir as “/opt/ftproot” and archiveDir as /opt/ftproot/archive”.
    The code is being run from Linux Machine1 as a schedule task.
    Please help.
    PFB the code snippet:
    package com.ftp;
    import com.thortech.xl.scheduler.tasks.SchedulerBaseTask;
    import org.apache.commons.net.ftp.*;
    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 java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    public class FTPService extends SchedulerBaseTask {
         private static String targetDir="";
         private static String archiveDir="";
    public void init() {
    public void execute() {
    try {
    String server = "Machine1
    String username = "username";
    String password = "password";
    String sourceDir = "C:\\Inetpub\\ftproot\\temp.txt";
    //String archiveDir = "/home/ftproot1";
    targetDir = getAttribute("Target Directory");
    FTPClient ftp = new FTPClient();
    * Connect to the server
    ftp.connect(server);
    ftp.login(username, password);
    System.out.println("Connected to " + server + ".");
    String[] names = ftp.listNames();
    for (String name : names) {
    System.out.println("Name = " + name);
    * Get all file names that are present in the current working directory
    FTPFile[] files = ftp.listFiles();
    String fileName = "";
    for (int i = 0; i < files.length; i++) {
    if (files.isFile()) {
    System.out.println("\t" + files[i].getName());
    File file = new File(targetDir + File.separator +
    files[i].getName());
    FileOutputStream fos = new FileOutputStream(file);
    * Copy the file to target system
    ftp.retrieveFile(files[i].getName(), fos);
    fos.close();
    fileName = files[i].getName();
    ftp.logout();
    ftp.disconnect();
    System.out.println("End of FTP....");
    System.out.println("Calling fileCopy()");
    System.out.println("Target Directory"+targetDir);
    fileCopy(fileName,targetDir);
    } catch (Exception e) {
    e.printStackTrace();
    public static String getDate() {
    String sdate = "";
    try {
         System.out.println("Inside getDate()");
    Calendar date = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat(
    "yyyy-MM-dd HH:mm:ss.0");
    sdate = formatter.format(date.getTime());
    } catch (Exception e) {
    return sdate;
    public void moveFile(String t) {
         try{
         System.out.println("inside moveFile");
    System.out.println("Moving Files");
    File fro = new File(t);
    archiveDir = getAttribute("Archive Directory");
    System.out.println("Archiving Directory"+archiveDir);
    File to = new File(archiveDir);
    boolean archived = fro.renameTo(new File(to, fro.getName()));
    if (archived) {
    System.out.println("FileArchived");
              /*String cmd="mv" +" "+t +" "+ "/home/ftproot/archive";
              System.out.println("Archive Directory"+archiveDir);
              System.out.println("Move Command"+cmd);
              Process SshProc =      (Runtime.getRuntime()).exec(cmd);
    } catch (Exception e) {
    e.printStackTrace();
    public void fileCopy(String filename,String Directory) {
         try{
         //String ifile="/home/ftproot/sunny.txt";
              String ifile=targetDir+"/"+filename;
         String ofile=ifile+"_"+getDate();
         File f1 = new File(ifile);
         File f2 = new File(ofile);
         InputStream in = new FileInputStream(f1);
         //For Append the file.
    //      OutputStream out = new FileOutputStream(f2,true);
         //For Overwrite the file.
         OutputStream out = new FileOutputStream(f2);
         byte[] buf = new byte[1024];
         int len;
         while ((len = in.read(buf)) > 0){
         out.write(buf, 0, len);
         in.close();
         out.close();
         System.out.println("File copied.");
         moveFile(ofile);
         }catch(Exception e)
         System.out.println("File copied."+e);
    Cheers,
    Sunny

    sunnyajmera wrote:
    Please help.If it was me....
    - You are connecting to a ftp server. I am guessing you didn't write that.
    - Get a flexible ftp client, there are many but make sure it shows you the ftp result codes.
    - Figure out how and if the ftp server will do what you want.
    If it does do what you want then ftp client will let you do the same thing.
    If that ftp server doesn't allow you to do it then you must do one of the following
    - Find a different server
    - Change the requirements
    - Find a way to impose the requirements using a tool in addition to ftp like some command executed through telnet.

  • Running System Commands using Java

    HI,
    I am developing an application using java which requires some system commands to be run.For example i have to write a java function which can program the windows scheduler to run a particular executable at some time & another one to initiate an ftp.I however do not know how to execute the corresponding commands from java.Is there any way or some specific api(similar to the system command in c) that i can use to perform these operations.I am using j2sdk 1.4.0_01 on a win 98 machine to develop the application.

    See [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html]java.lang.Runtime

  • FTP server in java doesn't work well at win os in some status.Why?

    As we know,FTP server in java used to use "BufferedOutputStream(socket.getOutputStream())" to complete data transfer.
    socket.getOutputStream() returns SocketOutputStream, and SocketOutputStream use native method:socketWrite0 to transfer data.
    I writted a FTP server in java that runs at win XP or win 2003 server. FTP client download file through internet,and when file size is large(for example, 5M),the download is failure. But I changed FTP server in C++,the download is ok. These PCs have multi network card commonly.
    In the first instance,I thinked my programm may be written wrong. But I have used CrossFTP and DanoFTP at sourceforge.net, they failed too.
    I have compared the source code of these FTP server and they are same in data transfer.
    There are another strange phenomenon.FTP server at some PC works well. For example,when I install FTP server at another PC.So I think that it is not link problem,and may be relate with PC's configuration?
    Any help appreciate.

    Win XP(sp2) and win 2003 server all have happened. Version of JDK is 6u2. I have doubted with version of JDK, and I changed to JDK 6u10 but problem is same.
    By the way, FTP server in C++ work well on these problem machine.
    I think the problem is related with configuration of machine(hardware or software), but I want to know where and why.
    Thanks for any help.

  • Calling Windows XP FTP Command in java

    Hi there!
    Need help in calling Windows XP FTP command in java:
    executing the FTP command in DOS works well, but when I tried calling it in java using Process and Runtime objects, it successfully transferred the files from remote to my local pc... but I seemed to be stuck with .exec() and cannot continue with the other statements.
    I know that I can use eFTPj or Apache Commons Net .. but I have no more time to study it since I have no more time left.
    Any idea or suggestion? I badly need your help�
    Take care and God bless,
    MaDz

    Solution:
    Better use Apache Commons Net - FTP for greater java support.

Maybe you are looking for