CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    TIP: Simple FTP server interaction

    NOTE: THis post contains code that uses nonstandard classes from the sun.net hierarchies. It is not guaranteed that the required classes will be present on all, or any Java2 distribution, or that behaviour will be consistent across deployments of the J2SDK

    -------

    Intro:

    While looking for a simple way to interact with an ftp server (i wasnt shifting hundreds of files) and not really wanting to write my own client I considered writing an extension to the URLConnection class, as HttpURLConnection exists, but Ftp apparently does not. (i also considered writing FTPFile and mimicking File for most things.. I may still)
    Anyways, i dscovered that FtpURLCOnnection DOES exist, but it is not standard, probably because the darn thing is so hard to ratify.

    I played with ti a while and decided to post this as a FYI for the community BUT ALSO TO RECEIVE SOME FEEDBACK from users who have maybe used this before, or have some ideas I have not tried.

    code:

    the following code snippet reads a file from an ftp server, and dumps it to the console (hint: try it with a SMALL binary or ascii file)
    Code:
    import java.net.*;
    import java.io.InputStream;
    public class FTPRead{
    
      public static void main(String[] argv)throws Exception{
        URL u = new URL("ftp://USER:PASS@HOST:PORT/PATH/TO/THEFILE");
        URLConnection uc = u.openConnection() ;
        uc.setDoInput(true);
        InputStream in = uc.getInputStream() ;
      
        byte[] buf = new byte[4096];
        for(int br = in.read(buf); br > -1; br = in.read(buf)){
          System.out.write(buf, 0 , br);
        }
        in.close();
      }
    }
    it appears that the user/pass needs embedding in the URL; i know of no way to pass it, as the classes in use are nonstandard, and i do not know if they use the Properties at all.
    There is virtually nothing you can do to protect this password either, if your source files are stolen.. So take care with this..


    Some code to read a DIRECTORY
    Code:
    import java.net.*;
    import java.io.InputStream;
    public class FTPRead{
    
      public static void main(String[] argv)throws Exception{
        URL u = new URL("ftp://USER:PASS@HOST:PORT/PATH/TO/THE/DIR/");
        URLConnection uc = u.openConnection() ;
        uc.setDoInput(true);
        InputStream in = uc.getInputStream() ;
      
        byte[] buf = new byte[4096];
        for(int br = in.read(buf); br > -1; br = in.read(buf)){
          System.out.write(buf, 0 , br);
        }
        in.close();
      }
    }
    it appears that, if the url has a trailing slash, a directory is assumed, and a listing is provided in the following format:
    -rwxrwxrwx 1 owner group 69414 Jan 15 6:01 030107cnd.exe
    rwxrwxrwx = permissions for local user (first rwx), group (2nd rwx) and everyone else (third rwx)
    when writing files, i have no iodea how to change these

    any client you write should parse this output and decide what group of people it belongs to



    the following code writes a file to the server:
    Code:
    import java.net.*;
    import java.io.OutputStream;
    public class FTPTest{
    
      public static void main(String[] argv)throws Exception{
        URL u = new URL("ftp://USER:PASS@HOST:PORT/PA/TH/TO/FI/LE/THEFILE") ;
        URLConnection uc = u.openConnection() ;
        uc.setDoOutput(true);
        OutputStream out = uc.getOutputStream() ;
      
        out.write("THIS DATA WILL BE WRITTEN TO FILE".getBytes());
        out.close();
      }
    }
    --
    Now, can anyone tell me how comphehensive the FtpURLConnection is? does it default to binary transfer mode, 777 permissions, username and pass another way etc.. ?
    Last edited by cjard; September 1st, 2004 at 06:27 AM.
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  2. #2
    Join Date
    Jul 2004
    Posts
    4

    FTp server connection

    import java.net.*;
    import java.io.InputStream;
    i tried ur code like this,

    public class FTPRead{

    public static void main(String[] argv)throws Exception{
    URL u = new

    URL("ftp://usernameasswd:ginnovationsindia.com/www/html/top.htm");
    URLConnection uc = u.openConnection() ;
    uc.setDoInput(true);
    InputStream in = uc.getInputStream() ;

    byte[] buf = new byte[4096];
    for(int br = in.read(buf); br > -1; br = in.read(buf)){
    System.out.write(buf, 0 , br);
    }
    in.close();
    }
    }

    but i get MalformedURLException. i specified port no as 21 too. still error

    Plz sort this out
    Thank u
    priya

    Also i am trying to connect to ftp thru proxy.but i cant do so with command line ftp program in dos prompt and also thru java program.
    proxy server is running on win 98 & proxy software is wingate.
    i setproxy host & port using System.setProperty() in java pgm .still not working

    Plz give me a solution

  3. #3
    Join Date
    Jul 2004
    Posts
    4

    FTp server connection

    URL u = new URL("ftp://ginnovationsindia:gin254ia@ginnovations.com:21/www/html/top.htm");
    I gave like this but error is

    Exception in thread "main" java.net.ConnectException: Connection timed out: conn
    ect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:292)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:158)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:145)
    at java.net.Socket.connect(Socket.java:391)
    at java.net.Socket.connect(Socket.java:349)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:142)
    at sun.net.NetworkClient.openServer(NetworkClient.java:121)
    at sun.net.ftp.FtpClient.openServer(FtpClient.java:390)
    at sun.net.ftp.FtpClient.<init>(FtpClient.java:670)
    at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.ja
    va:176)
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnec
    tion.java:260)
    at FTPRead.main(FTPRead.java:9)

    why so??

  4. #4
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104
    why did the connection time out? because packets disappeared into oblivion on the network.. ensure that you can directly connect to the ftp server. your other posting leads me to believe that you cant.. which is probably 99.9% of the problem..

    C:\Documents and Settings\admin>ftp
    ftp> o 209.157.71.50
    > ftp: connect :Unknown error number
    ftp> o ginnovations.com
    > ftp: connect :Unknown error number
    ftp>
    firewalled/dead
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  5. #5
    Join Date
    Aug 2004
    Posts
    24

    Re: TIP: Simple FTP server interaction

    Code:
    import java.net.*;
    import java.io.OutputStream;
    public class FTPTest{
    
      public static void main(String[] argv)throws Exception{
        URL u = new URL("ftp://USER:PASS@HOST:PORT/PA/TH/TO/FI/LE/THEFILE") ;
        URLConnection uc = u.openConnection() ;
        uc.setDoOutput(true);
        OutputStream out = connect.getOutputStream() ;
      
        out.write("THIS DATA WILL BE WRITTEN TO FILE".getBytes());
        out.close();
      }
    }
    okay when i go to compile this peice of code i get an varible error with connect.getOutputStream(); i dont think that connect is spossed to be a user diffend var, so can you explane

  6. #6
    Join Date
    Feb 2004
    Location
    USA - Florida
    Posts
    729

    Re: TIP: Simple FTP server interaction

    You did not define connect anywhere in your program. Perhaps you mean:
    Code:
    OutputStream out = uc.getOutputStream()
    ?
    Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html

  7. #7
    Join Date
    Aug 2004
    Posts
    24

    Re: TIP: Simple FTP server interaction

    thanks, that works.

    Alir

  8. #8
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: TIP: Simple FTP server interaction

    my apol.. looks like i left a varaible name in there from the "unfriendly" version of the code..
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  9. #9
    Join Date
    Aug 2004
    Posts
    24

    Re: TIP: Simple FTP server interaction

    okay i have been using the ftp programes above in a applaction verision. But now when i try and use them in an applet i get java.security.AccessControlException: access denied

    does any one know what i can do to stop this from happening

    Alir

  10. #10
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: TIP: Simple FTP server interaction

    applets may only connect to the server that served them. this means if your website is www.alirblack.com and youre attempting to connect to ftp.microsoft.com, youll get an acces denied error

    several solutions:

    run your webserver and ftp server on teh same machine (easiest)
    run a proxy on the webserver to the real ftp server (harder)
    dont use an applet (always a good idea; applets are retarded)
    allow the security restriction (hard. dont ask me about it.. start a new thread if you want an answer)
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  11. #11
    Join Date
    Aug 2004
    Posts
    24

    Re: TIP: Simple FTP server interaction

    thanks man, i guess i have to make a choice then right?

  12. #12
    Join Date
    Feb 2005
    Posts
    1

    Question Re: TIP: Simple FTP server interaction

    hI,

    I am interested in sending a file from a user's PC to a server. i wanted to know if I can edit the code where you send the string data to read some data from a text file and send that data to a specific file on the webserver. Can you help me ? I amnew to Java ..also is it possible to get a fiel form a user's PC in a servlet?
    thanks,
    anonsu

  13. #13
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: TIP: Simple FTP server interaction

    Quote Originally Posted by anonsu
    hI,

    I am interested in sending a file from a user's PC to a server. i wanted to know if I can edit the code where you send the string data to read some data from a text file and send that data to a specific file on the webserver. Can you help me ?

    the following code reads from a file:


    Code:
    FileInputStream fis = new FileInputStream("C:\testfile.exe");
    byte[] buffer = new byte[4096];
    
    for(int bytesRead = fis.read(buffer); bytesRead > -1; bytesRead = fis.read(buffer){
    
      //the buffer contains up to 4096 bytes of data from the file
      <some output destination>.write(buffer, 0, bytesRead);
    
    }
    fis.close();
    what destination you write to is up to you.. to write the bytes to the server, you would write them to the 'out' output stream

    I amnew to Java ..also is it possible to get a fiel form a user's PC in a servlet?
    thanks,
    anonsu
    no. servlets cannot get files from user PCs, but they can receive them if the user sends them. While you may not see a difference, there is a defined and clear one in terms of client and server roles.
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  14. #14
    Join Date
    Jun 2009
    Posts
    1

    Re: TIP: Simple FTP server interaction

    Hi

    I need to write 2 files to 2 different directories in my ftp server,
    but the path to the destination file is already predefined in the
    URL - PA/TH/TO/FI/LE/THEFILE
    URL u = new URL("ftp://USER:PASS@HOST:PORT/PA/TH/TO/FI/LE/THEFILE") ;
    How can i change the destination directories dynamically?

    Your help will beappreciated

  15. #15
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: TIP: Simple FTP server interaction

    I have this class for FTP (see attached FTP.java) that you can use to open a connection to a server and send commands, as with an FTP client.

    For instance, use it in a program like this:

    Code:
    ...
    	// start the FTP session; host is the remote server name
    	FTP ftp = new FTP(host);
    	// login
    	ftp.user(ftpUsr, ftpPwd);
    	// change to binary mode
    	ftp.binary();
    	// write a file to the remote server
    	ftp.put(localFile, remoteFile);
    	// change to another folder in the server
    	ftp.cd(remoteDir);
    	// write several files (localFiles may have wildcards)
    	ftp.mput(localFiles);
    	// close the connection
    	ftp.logout();
    ...
    Attached Files Attached Files

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured