[HELP] Download file from FTP server

hi,
I want to write a java program that can download and upload files from ftp server. Currently I only manage to upload a file to ftp server but i cant download file from ftp server. Here is the source code that only allow user to upload file. Anyone can give me some guidelines so that my program can download and also upload file? thx.
import java.io.*;
import java.net.*;
public class FTPUpload {
private static final int CTRLPORT = 21;
private static Socket ctrlSocket;
private static PrintWriter ctrlOutput;
private static BufferedReader ctrlInput;
private static byte[] localHostAddress;
public final static String DIR = "C:\\zip\\";
public static void main(String[] args) {
try {
String host = "192.168.1.1";
String loginName = "testuser";
String password = "password";
String dirName = "/home/testuser";
String fileName = "hello.zip";
ctrlSocket = new Socket(host, CTRLPORT);
localHostAddress = ctrlSocket.getLocalAddress().getAddress();
ctrlOutput = new PrintWriter(ctrlSocket.getOutputStream());
ctrlInput = new BufferedReader(new InputStreamReader(ctrlSocket.getInputStream()));
ctrlOutput.println("USER " + loginName);
ctrlOutput.flush();
ctrlOutput.println("PASS " + password);
ctrlOutput.flush();
ctrlOutput.println("CWD " + dirName);
ctrlOutput.flush();
ctrlOutput.println("TYPE I");
ctrlOutput.flush();
FileInputStream fis = new FileInputStream(DIR + fileName);
Socket dataSocket = dataConnection("STOR " + fileName);
OutputStream outstr = dataSocket.getOutputStream();
int n;
byte[] buff = new byte[1024];
while ((n = fis.read(buff)) > 0) {
outstr.write(buff,0,n);
dataSocket.close();
fis.close();
ctrlOutput.close();
ctrlInput.close();
ctrlSocket.close();
}catch (Exception e) {
e.printStackTrace();
private static Socket dataConnection(String ctrlcmd)
throws IOException,UnknownHostException {
String cmd = "PORT ";
ServerSocket serverDataSocket = new ServerSocket(0,1);
for (int i=0;i<4;i++) {
cmd = cmd + (localHostAddress[i] & 0xff) + ",";
cmd = cmd + (((serverDataSocket.getLocalPort())/256) & 0xff)
+ ","
+ (serverDataSocket.getLocalPort() & 0xff);
ctrlOutput.println(cmd);
ctrlOutput.flush();
ctrlOutput.println(ctrlcmd);
ctrlOutput.flush();
Socket dataSocket = serverDataSocket.accept();
serverDataSocket.close();
return dataSocket;
}

Or just use a java.net.URL("ftp://...) ..., get its input stream, and away you go ...

Similar Messages

  • Problem in download file from FTP server

    Hi
    I want to download a file from FTP server for that i am using the apache FTP module but i am not getting how to download a file with that api i can dispaly the list of files and folders but not able to download the file or folder can any one help me in this
    Thanks
    Ninad

    Hi
    I think you miss understood something I am writing a program to download the file in Java where i have used the jakarta.apache api for that and getting problem in that bellow is the code where I have written to print the directory & file names but I don't know how to download the file
    FTPClient ftpConnection = new FTPClient();
    ftpConnection.connect(host);
    ftpConnection.login(FTPConnection.userName,FTPConnection.password);
    FTPFile fileList[] = ftpConnection.listFiles();
    for(int i=0;i<fileList.length;i++)
         System.out.println(fileList.getName());
    thanks
    Ninad

  • Downloading file from ftp server

    hii
    how do i download the file from ftp server. plz suggest wat are the function modules for tht.. and plz do give the values of the parameters used in the fn modules
    points guranteed:-)

    <i><b>*--> Scramble the password.</b></i>
      CALL FUNCTION 'SCRAMBLE_STRING'
           EXPORTING
                source = password
                key    = 26101957
           IMPORTING
                target = password.
    <i><b>*--> Connect to the FTP server.</b></i>
    <i>*  user is the logon user for the FTP server.
    password is the password you have just scrambled.
    host is the ip address of the FTP server.
    rfc_destination is 'SAPFTPA'.</i>
      CALL FUNCTION 'FTP_CONNECT'
           EXPORTING
                user                = user
                password        = password
                host                = host
                rfc_destination = rfc_destination
           IMPORTING
                handle          = wa_handle
           EXCEPTIONS
                not_connected   = 1
                OTHERS          = 2.
    <i><b>*--> Carry out the command on the FTP server</b></i>
    <i>*  wa_command is the command you wish to carry out on the FTP server (e.g.   
    wa_command = 'ascii' will specify ascii mode).  Result_itab will contain the
    result of your commands.</i>
      CALL FUNCTION 'FTP_COMMAND'
           EXPORTING
                handle           = wa_handle
                command       = wa_command
           TABLES
                data          = result_itab
           EXCEPTIONS
                tcpip_error   = 1
                command_error = 2
                data_error    = 3
                OTHERS        = 4.
    <b>*--> Disconnect from the target host.</b>
      CHECK NOT wa_handle IS INITIAL.
      CALL FUNCTION 'FTP_DISCONNECT'
           EXPORTING
                handle = wa_handle
           EXCEPTIONS
                OTHERS = 1.
    <u><i><b>Hope this helps :)</b></i></u>

  • Download file from FTP Server to Application Server

    Hi Friends,
    Using the standard SAP Program RSFTP002, I was able to download the file to my local PC. But my requirement is to download the file from FTP to application server.
    For RSFTP002, I am passing the username, password, host and in command 1 I am passing lcd :\temp, command 2 get filename. The file gets downloaded into c:\temp. If I do the same passing the app server path in command 1 as /usr/sap/tmp I get an error that pass cannot be found.
    Anyone please help me how to donload the file from ftp to app server.
    Thanks,
    Deepthi

    If I remember correctly the activation type on the technical settings tab must be set to "start on application server" in transaction SM59 for the RFC destination for the FTP server.  This should allow the files to be transferred to/from the application server.
    Regards,
    Steve.

  • Problem with downloading file from FTP server

    Hello all
    I have uploaded a file from an application i developed and i want to download this file from another application. The code is
    public static void FTPcon() throws FtpException{
       String hostname = "my.ftp.server";
       String username = "myusername";
       String password = "mypass";
       Ftp ftp = new Ftp(hostname,username,password);
       ftp.setHostname(hostname);
            ftp.setUsername(username);
            ftp.setPassword(password);
            ftp.connect();
            ftp.setBinary();
            ftp.download("file.dat");
            ftp.disconnect();
    }The error i receive is java.io.FileNotFoundException: public.dat (The system cannot find the file specified) but the file is on the server.
    Thanks in advance for any help

    Cotton thank you for your reply
    Any other sugestions please?The server disagrees. So...
    - the file does not existThe file exists.I checked it with an FTP client program.
    - the file has a different nameThe file name is correct
    - you are connected to the wrong serverI am connecting to the correct server
    - you are in the wrong ftp directoryThe file is placed in the home directory
    - the ftp library you are using is broken (less
    likely)I am using the library from jscape.I dont think is broken because i can upload the file from the first application.
    >
    FTP isn't somehow broken in Java. I use it all the
    time. The problem is something listed above. I would
    check all of the first four if I were you because
    that's most likely where the problem is.Message was edited by:
    flightcaptain

  • Download file from ftp server

    Can I download files from an ftp server by simply using the ip address or https:// url?    I've only gotten this to work by using the "ftp//:" address in previous projects and I'm not getting this to work in many different attempts. 
    Here is one...
     # FTP Config
    $FTPHost =
    "10.10.10.5"
    $Username =
    "admin"
    $Password =
    "12345678"
    $FTPFile =
    "test.log"
    # FTP Log File Url
    $FTPFileUrl =
    "ftp://" +
    $FTPHost +
    "/" +
    $FTPFile
    # Create FTP Connection
    $FTPRequest =
    [System.Net.FtpWebRequest]::Create("$FTPFileUrl")
    $FTPRequest.Credentials
    = New-Object System.Net.NetworkCredential($Username,
    $Password)
    $FTPRequest.Method =
    [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $FTPRequest.UsePassive
    = $false
    $FTPRequest.UseBinary
    = $true
    $FTPRequest.KeepAlive
    = $false
    # Get FTP File
    $FTPResponse =
    $FTPRequest.GetResponse()
    $ResponseStream =
    $FTPResponse.GetResponseStream()
    $FTPReader =
    New-Object System.IO.Streamreader
    -ArgumentList $ResponseStream
    do
    Write-Host
    $FTPReader.ReadLine()
    while ($FTPReader.ReadLine()
    -ne $null)
    $FTPReader.Close()
    # Create FTP Connection
    $FTPRequest =
    [System.Net.FtpWebRequest]::Create("$FTPFileUrl")
    $FTPRequest.Credentials
    = New-Object System.Net.NetworkCredential($Username,
    $Password)
    $FTPRequest.Method =
    [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $FTPRequest.UsePassive
    = $false
    $FTPRequest.UseBinary
    = $true
    $FTPRequest.KeepAlive
    = $false
    # Get FTP File
    $FTPResponse =
    $FTPRequest.GetResponse()
    $ResponseStream =
    $FTPResponse.GetResponseStream()
    $FTPReader =
    New-Object System.IO.Streamreader
    -ArgumentList $ResponseStream
    do
    Write-Host
    $FTPReader.ReadLine()
    while ($FTPReader.ReadLine()
    -ne $null)
    $FTPReader.Close()

    Hi!
    You don't need to specifically use an IP address. E.g can use
    $FTPHost = "myrandomserver.mycompany.com"
    $Username = "admin"
    $Password = "12345678"
    $FTPFile = "test.log"
    # FTP Log File Url
    $FTPFileUrl = "ftp://" + $FTPHost + "/" + $FTPFile

  • Need to copy .txt file from FTP server and downloaded on local server directory.

    I need to figure out a way to copy .txt file from ftp server in local server directory using sql jobs.

    Below links will help achieving it:
    https://www.virtualobjectives.com.au/sqlserver/ftp_scripts.htm
    http://www.mssqltips.com/sqlservertip/2884/sql-server-integration-services-ssis-ftp-task-for-data-exchange/

  • How to read .xls file from FTP server t oInternal table

    Hi
    am using the FTP_SERVER_TO_R3 to read xls file from FTP server to internal table
    but the data i get in LT_TEXT is special characters.
    CALL FUNCTION 'FTP_SERVER_TO_R3'
    EXPORTING
    handle = hdl
    fname = f_name "ProdDataFromCRM.xls.
    * CHARACTER_MODE = 'X'
    * IMPORTING
    * BLOB_LENGTH =
    TABLES
    BLOB = lt_text
    * TEXT = lt_text
    EXCEPTIONS
    TCPIP_ERROR = 1
    COMMAND_ERROR = 2
    DATA_ERROR = 3
    OTHERS = 4
    can any one help me out to get the exact data..
    Really appreciate your quick response..
    Thank You

    Hi, if you really retrieve an excel file, you can not see the data in ABAP. You may see them in Excel. For this you may use
    CALL METHOD document->open_document_from_table
    of the interface i_oi_document_proxy for OLE objects. You can access the data with reference to the interface i_oi_spreadsheet.
    Please check [Desktop Office Integration (BC-CI)|http://help.sap.com/printdocu/core/Print46c/en/data/pdf/BCCIOFFI/BCCIOFFI.pdf] for details.
    But, who knows, perhaps you want "And Now For Something Completely Different".
    Regards
    Clemens

  • How to get file from FTP Server using File Control

    Hi,
    Any one did getting file from FTP Server?
    Please let me know any one help me.
    I would need to get file from FTP Server.
    Thanks,
    Madhu

    Yes I have done that. But In FTP Server I cannt read file, because no previliges. Only I need to copy file from FTP Server to local server then only I can read that file.
    I tried all options using FileConrol(getFiles(),read()).
    getFiles() - It wont copy the file, it give information about file.
    read() - I dont have previliges to read the file.
    Please tell me any other procedure would be there for getting file from FTPServer.
    Thanks,
    Madhu

  • Upload XL file from FTP server

    Hi All,
    Can anybady help me, how to upload Excel file from FTP server.
    Thanks
    Sri
    Edited by: srikanthn on Apr 14, 2010 6:31 PM

    Hello
    How about using SAPFTP?
    I hope SAP note 130106 will guide you on this.
    Thanks
    koju

  • Regaring file from FTP server to application server

    Hi frnds,
    Below is my code where i am transferring Presentation server file to FTP server.
    Now i want to transfer that file from FTP server to application server.
    any help. below i am providing my code.
    <code>
    *& Report  demo
    report  z_demo_ftp.
    Variables declaration
    data : mi_handle type i,
           pwd       type char30,
           slen      type i,
           key type i value 26101957,
           it_file2 type filetable,
           w_file2 like   line of it_file2,
           l_rc type i,
           v_index type i,
           v_file(30) type c,
           v_path(100) type c,
           v_path_tmp(100) type c.
    *Internal table declaration
    data: begin of mtab_data occurs 0,
           line(132) type c,
          end of mtab_data.
    Selection scree parameters
    parameters: p_file type string default 'C:\'.
    Get the file path
    at selection-screen on value-request for p_file.
      data: p_file1 type string.
      p_file1 = p_file.
      call method cl_gui_frontend_services=>file_open_dialog
        exporting
          default_filename        = p_file1
        changing
          file_table              = it_file2
          rc                      = l_rc
        exceptions
          file_open_dialog_failed = 1
          cntl_error              = 2
          error_no_gui            = 3
          not_supported_by_gui    = 4.
      if sy-subrc <> 0.
        message id sy-msgid type sy-msgty number sy-msgno
                with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      else.
        read table it_file2 into w_file2 index 1.
        p_file = w_file2-filename.
        clear w_file2.
        refresh it_file2.
        split p_file at '\' into table it_file2.
        describe table it_file2 lines v_index.
        read table it_file2 into w_file2 index v_index.
        concatenate 'put' w_file2-filename into v_file separated by space.
        delete it_file2 index v_index.
        clear w_file2.
        loop at it_file2 into w_file2.
        if sy-tabix = 1.
        v_path = w_file2-filename.
        endif.
        if sy-tabix ge 2.
        concatenate v_path '\' w_file2 into v_path.
        endif.
        endloop.
        concatenate 'lcd' v_path into v_path_tmp separated by space.
      endif.
    Start of selection
    start-of-selection.
    pwd = 'file456'.
    slen = strlen( pwd ).
    call function 'HTTP_SCRAMBLE'
      exporting
        source      = pwd
        sourcelen   = slen
        key         = key
      importing
        destination = pwd.
    Connect to FTP
    call function 'FTP_CONNECT'
      exporting
        user            = 'client'
        password        =  pwd
        host            = 'saturn'
        rfc_destination = 'SAPFTP'
      importing
        handle          = mi_handle
      exceptions
        not_connected   = 1
        others          = 2.
    if sy-subrc = 0.
    Excute FTP command
    call function 'FTP_COMMAND'
        exporting
          handle        = mi_handle
          command       = 'cd staff
        tables
          data          = mtab_data
        exceptions
          tcpip_error   = 1
          command_error = 2
          data_error    = 3
          others        = 4.
    Excute FTP command
          call function 'FTP_COMMAND'
        exporting
          handle        = mi_handle
          command       = v_path_tmp
        tables
          data          = mtab_data
        exceptions
          tcpip_error   = 1
          command_error = 2
          data_error    = 3
          others        = 4.
    Excute FTP command
      call function 'FTP_COMMAND'
        exporting
          handle        = mi_handle
          command       = v_file
        tables
          data          = mtab_data
        exceptions
          tcpip_error   = 1
          command_error = 2
          data_error    = 3
          others        = 4.
      if sy-subrc = 0.
        loop at mtab_data.
          write: / mtab_data.
        endloop.
      endif.
    endif.
    *FTP disconnect
    call function 'FTP_DISCONNECT'
      exporting
        handle = mi_handle
      exceptions
        others = 1.call function 'FTP_DISCONNECT'
      exporting
        handle = mi_handle
      exceptions
        others = 1.
          end-of-selection.
    </code>
    so what more code shuld i write.
    regards,
    kamal

    Hi Che Eky  ,
                          Actually the above code is for putting the presentation server file to FTP Server.
    But now i need to Put the same file present in the FTP server to Application server.
    So any help or code which will be helpful.
    regards,
    kamal

  • Read File From FTP Server

    Hi all,
    I have to read a file from FTP server, manipulate it and then create another file at the same location.
    Currently, I am able to write a file onto FTP server ..but how do I read the file?
    Any help will be greatly appreciated.
    Thanks,
    Haritha

    can i know how do u placing the file in FTP?
    ( default path specified in the FTP server, it might be Pre. server address)

  • Files from FTP server to Application server

    Hi All,
    I am new to SDN and SAP XI, can anyone tell me whether its possible to move the files (different strcuture files i.e. some are master data files and some are transaction data file) from FTP server to Application server with one interface. Actually the process is already established at clientsite for placing master data files like product, plant etc from FTP server to App server through FTP adapter. Now my requirement is to move transaction data file with completely different structure as master data to App server. If we place these trasaction data file in same folder/directory as master data files does SAP XI pick this file also. If not what are the steps I need to follow to achieve this. I know that if we create new configuration it will work but I question is does master data interface picks this transaction data file also.
    Right now our process for master data files is SAP XI picks the files and deletes the file from FTP server folder. The master data file names are plant_attr.csv, product_attr.csv etc and transcation data file name is salestrasactiondata.csv. I need to move these files to application server on daily bases.
    I appreciate your help .
    Regards
    Bob.

    > I am new to SDN and SAP XI, can anyone tell me whether its possible to move the files (different strcuture files i.e. some are master data files and some are transaction data file) from FTP server to Application server with one interface.
    Hello Bob,
    Yes it is possible.
    There can be two ways of doing it.
    1. N:1 mapping, BPM will require for this.
    N:1 Mapping refer this blog
    IDOCs (Multiple Types) Collection in BPM
    BpmPatterns CollectMerge
    part1  BPM with Patterns explained Part-1
    part2  BPM with Patterns explained Part-2
    Second option
    Create 3 scanarios in integration directory and correspondingly in integration repositoy create different data types, message types, mappings & interface mappings and then in each of scenario us different message interface and interface mapping.
    > I know that if we create new configuration it will work but I question is does master data interface picks this transaction data file also.
    >
    If you are using N:1 scenario then use *.csv in your sender adapter under file name parameter and then all the files will be picked up from same directory.
    If you are using second option (3 different scenarios) then also you can pick the different files from same directory. You will be having 3 sender adapters in this case, So, one for picking master data, and another for product data and the last one for transaction data.
    So, in case of master data use "plant_*.csv" as a file name and directory name.
    In case of product data, use "product_*.csv " as a file name and source directory will remain same.
    similarly do it for transaction data.
    So by this way all 3 sender adapters will perform their job to pick the different files from same source directory.
    Regards,
    Sarvesh

  • Error in PDF Conversion while downloading file from application server

    Hi,
    I am facing a problem in which i have to download file from application server which is a PDF file (output of SAP Script). I am downloading this file using following code in BSP technology:
    * event handler for data retrieval
    EMPCD = REQUEST->GET_FORM_FIELD( 'emp' ).
    MONTH = REQUEST->GET_FORM_FIELD( 'mn' ).
    YEAR  = REQUEST->GET_FORM_FIELD( 'yr' ).
    W_IND = 'N' .
    DATA : wa_zform16 type  zform16.
    DATA : file_path type string.
    DATA : l_pdf_len type string.
    DATA STR TYPE STRING.
    DATA: OUTPUT    TYPE STRING ,
          L_XSTRING TYPE XSTRING ,
          APP_TYPE  TYPE STRING.
    DATA: PDF_TABLE TYPE  RCL_BAG_TLINE.
    DATA PHY_NAME_OUT     TYPE SAPB-SAPPFAD.
    concatenate '/usr/sap/put/form16/' EMPCD '_' YEAR '.PDF'  into file_path
    *PHY_NAME_OUT = '/usr/sap/put/form16/01000200_2007.PDF'.
    PHY_NAME_OUT = file_path.
    OPEN DATASET PHY_NAME_OUT FOR INPUT IN TEXT MODE ENCODING default.
    IF SY-SUBRC IS INITIAL.
      DO.
        READ DATASET PHY_NAME_OUT INTO STR.
        IF SY-SUBRC IS INITIAL.
          CONCATENATE
              OUTPUT
              STR
              CL_ABAP_CHAR_UTILITIES=>CR_LF
          INTO OUTPUT.
        ELSE.
          EXIT.
        ENDIF.
      ENDDO.
      APP_TYPE = 'APPLICATION/PDF'.
      CALL FUNCTION 'SCMS_STRING_TO_XSTRING'
        EXPORTING
          TEXT     = OUTPUT
                MIMETYPE = 'APPLICATION/PDF'
    *            MIMETYPE = 'APPLICATION/PDF;charset=utf-16le'
        IMPORTING
          BUFFER   = L_XSTRING.
      CALL METHOD CL_BSP_UTILITY=>DOWNLOAD
        EXPORTING
          OBJECT_S            = L_XSTRING
          CONTENT_TYPE        = APP_TYPE
          CONTENT_DISPOSITION = 'attachment;filename=webforms.pdf'
          RESPONSE            = _M_RESPONSE
          NAVIGATION          = NAVIGATION.
    Result of this code is : there is a pop up asking to open or save pdf format and process is complete, but i have problem in downloaded file.
    At the time of creation i have put BMP image for signature in PDF file and it is working fine but when i upload that file in Application server and then download it with above used code it save the PDF file but when i open that file so whereever i have used signature that page gives error and could not display that scanned signature.
    Can anyone please help me in this regard.
    or is there any possibility from which i can download that file just like File transfer from BSP.
    Keep in mind that i am using BSP technology so all GUI based function module to download file are not working.
    waiting for your reply.....
    Regards,
    Gagan

    Hi Raja,
    I have standard sap form for TDS Certificate on which i have include an BMP image for digital signature and download that script into pdf format.While i download that PDF looks ok but it is not working in BSP.
    Regards,
    Gagan

  • Tcode for downloading file from BW server

    hi
    can nay tell me what is the T-CODE  to download file from BW server to my PC.
    REMOVED
    regards
    sampath

    There isn't a transaction.
    You can see the example report to execute ftp on BW server.
    server to server
    or
    client to server.
    the reports are named like:
    rsftp001
    rsftp002
    rsftp011
    Regards,
    Sergio

Maybe you are looking for

  • How to hide url of third party external/partner application

    I have a third party external oracle application arcims by the esri corporation that I have on a test portal. It has it's own password authentication. In order to have sso work i have to turn off its password request. The problem is that the URL addr

  • Adobe reader 11 printing black text as green

    I have checked accessability and the replace document colors is not checked.  For a time after I downloaded reader 11 black text printed black but today it has reverted to green. I have also tried two other actions.  First, copied PDF document to cli

  • Formula variable for date in report

    Hi All, I have to display the last date value of a particular date in the report. For a better understanding, I have Customer, Equipment, Service date, Amount In the report, I have to display Customer, Equipment, Last Service date, Last Service Amoun

  • Unable to create a test  via Content Management via Content Administration

    I am unable to create a test or survey via Content Management via Content Administration because insufficient privileges message. I create the folder and enter the test information for creating a test and then I after I click apply. I get message "Yo

  • New Email Format

    Rather than an idea, this is a plea for help because I was unable to find another place through Online Support to make a complaint. The changes recently made to the email format (around 1/20/2011) for how to select email contacts when trying to send