Transfering a file through Socket programming

Hi all,
I want to return a file from server to client through a socket. I tried using ObjectOutput Stream where in I returned a java.io.File from server. But at client side when I say file.getLeangth() it comes as 0 and if I try to assign FileInputStream on the object it throws an exception as the file not found as the path associated with the file will be of Server.
So can anyone help as to how to transfer a file through socket programming???
thx in advance
MK

java.io.File is NOT the contents of the file. It really just represents the path.
If you want to transfer the file's contents, you'll have to use a FileInputStream or FileReader, read from it, and then write the bytes or chars on the wire.

Similar Messages

  • Tansfer files through socket

    Hi all
    Can anyone tell me that how can i send files from server to the client through socket programming.
    if u recommend to send file using
    int read(byte[] b, int offset, int blength)
    void write( byte[] b, int offset, int blength) then how plz tell me how can use these methods to send a receive files??? if u give a small example code then i will very greatful to u.
    Usman

    Thanks for ur help.
    but i have got it. i have designed a client and server. Client requests the server to send a specif file (Client takes the path of file from user). And server sends the file to the client.
    I have checked this program on many files. like *.exe, *.txt, *.dat, *.zip, *.mp3, *.jpg.
    it worked smoothly. I have test to trasfer a file of 700MB and it worked correctly.
    Ooops! i did not check it on Network. i run these program on my own computer. both client and server were running on same computer.
    but i am facing a little problem. that is: the speed of trasfering the files is very slow.
    any1 know how to increase the speed of data transfer over the sockets ???
    And plz tell me how can i trasfer a complete directory just as i trasfered file over the sockets. (Remember: a dircetory may or may not contains may other files and also other directories
    thanks in advance...!!!
    here is the code:
    *          CLIENT            *
    import java.net.*;
    import java.io.*;
    public class TransferClient
        public static void main(String[] args)
            try
                 int fileSize = 0;
                 int readBytes = 0;     
                 final int BUFFER_SIZE = 512;
                 byte[] buffer = new byte[BUFFER_SIZE];       
                   Socket sockClient = new Socket(InetAddress.getLocalHost(),2000);     
                   DataInputStream dataInputStream = new DataInputStream(sockClient.getInputStream());
                   BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("filename.ext"));
                   BufferedReader inputUser   = new BufferedReader(new InputStreamReader(System.in)); //For User input
                   PrintWriter output = new PrintWriter (sockClient.getOutputStream(), true);     //To send the user input to the server
                   //get path from user
                   System.out.print("Enter the complete path of file: ");
                   String path = inputUser.readLine();
                   //send path to server
                   output.println(path);
                   readBytes = dataInputStream.readInt();
                   while(readBytes > 0)
                        readBytes = dataInputStream.read(buffer, 0, readBytes);
                        fileSize = fileSize + readBytes;
                        bufferedOutputStream.write(buffer, 0, readBytes);
                        readBytes = dataInputStream.readInt();
                   }//end while
                   bufferedOutputStream.flush();
                   System.out.println("Received Bytes:  " + fileSize);
                   dataInputStream.close();
                   bufferedOutputStream.close();                              
                   inputUser.close();
                   output.close();
                   sockClient.close();
            }//end try
            catch(IOException ioException)
                 ioException.printStackTrace();
            }//end catch
        }//end main()
    }//end class TransferClient
    *          SERVER            *
    import java.io.*;
    import java.net.*;
    public class TransferServer
        public static void main(String[] args)
             int fileSize = 0;         
             int readBytes = 0;
             final int BUFFER_SIZE = 512;
             byte[] buffer = new byte[BUFFER_SIZE];
             try
                  ServerSocket ss = new ServerSocket(2000);
                  System.out.println("Server Strarts...");
                  Socket sock = ss.accept();
                  BufferedReader clientInput = new BufferedReader(new InputStreamReader (sock.getInputStream()));
                   DataOutputStream dataOutputStream = new DataOutputStream(sock.getOutputStream());
                   PrintWriter output = new PrintWriter(sock.getOutputStream(), true);
                   System.out.println ("Connection Received");          
                   String path = clientInput.readLine();               
                   File f = new File(path);                    
                   if( f.exists() )
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path));               
                        while((readBytes = bufferedInputStream.read(buffer))!= -1)
                             fileSize = fileSize + readBytes;
                             dataOutputStream.writeInt(readBytes);
                             dataOutputStream.write(buffer, 0, readBytes); 
                        }//end while
                        dataOutputStream.writeInt(0);          
                        System.out.println("Sent Bytes:  " + fileSize);
                        bufferedInputStream.close();
                   }//end if
                   clientInput.close();
                   dataOutputStream.close();
             }//end try
             //catch(FileNotFoundException fileNotFoundException)
             //     output.println("Sorry! file does not exist.");
             catch(IOException ioException)
                  ioException.printStackTrace();
             }//end catch       
        }//end main()
    }//end class TransferServer

  • How to compile dunamically genrated java files through java program?

    Hi, I have a requirement where i generate java files from WSDL dynamically using wsdl2java jaxbri. I need to compile these files dynamically on the fly and jar it. Everything should happen through java program. Bcos everything is dynamic here, no information is known (like dir, file names ...) until the runtime. Everything is user fed.
    the directories may contain other directories with java files. its recursive
    i tried com.sun.tools.javac.Main.. but either its not scaling to my needs or i donno how to wok with this.
    is there any option to compile the java files as they are created thru JAXBRI (wsdl2java)?
    any help is appreciated..
    -s

    my requirement is :
    i create java files from wsdl2java (axis).. i need to compile all the java files.. directories with in the directories (recursive)...
    as bcos the the java files have inter-dependencies they have to be compiled as a bunch something like (java *.java). I donno how to do this in javac.Main tool
    Once all these files are compiled i need to create a jar out of them
    Any help is appreciated!

  • Send files through Sockets

    how do i send an entire file through a socket...?
    thank you....

    [http://forums.sun.com/thread.jspa?forumID=11&threadID=390636] this may help you

  • Logic to run Unix script file through ABAP program

    Hi Friends,
    I need to run the Unix script file from abap program, for that user provided file directory of application server.
    Is there any logic/FM  to run through abap programing.
    pls can any one provide logic.
    Thanks,
    Ravi

    report zsrchsap.
    *-This is a demo report for Search Sap
    *-Author : Sandeep Kulkarni
    *-Date : 09/20/2001
    parameters : p_sfile(60) lower case
              "File to be moved
              "Eg : /home/in/SFILE1.txt
                p_dfile(60) lower case.
              "File's Destination
              "Eg: /home/archive/SFILE1.txt
    data : t_btcxpm
           like btcxpm occurs 0,
           p_addparam
           like sxpgcolist-parameters.
      concatenate
      '/home/ABAP/scripts/Archive_file.sh'
      p_sfile
      p_dfile
      into p_addparam separated by space.
      refresh t_btcxpm. clear t_btcxpm.
      call function 'SXPG_CALL_SYSTEM'
        exporting
          commandname = 'ZSHELL'
          additional_parameters = p_addparam
        tables
          exec_protocol = t_btcxpm
        exceptions
          no_permission              = 1
          command_not_found          = 2
          parameters_too_long        = 3
          security_risk              = 4
          wrong_check_call_interface = 5
          program_start_error        = 6
          program_termination_error  = 7
          x_error                    = 8
          parameter_expected         = 9
          too_many_parameters        = 10
          illegal_command            = 11
          others                     = 12.
      if sy-subrc = 0.
        write : /
        'File',p_sfile,'moved to',p_dfile.
      else.
        write : / 'Error Occured'.
      endif.

  • Data are not transfered as unicode through sockets

    I have aplication with connection through sockets. I use PrintWriter and BufferedReader for writing and reading data, created lik this:
    pw = new PrintWriter( skt.getOutputStream(), true );
    br = new BufferedReader( new InputStreamReader( skt.getInputStream() ) );
    When I send data I put this code for checking:
    int tmpSize = str.length();
    for( int i = 0; i < tmpSize; i++ )
         char chr = str.charAt( i );
         int tmpInt = (int)chr;
         System.out.print( tmpInt + " " );
    System.out.println();
    pw.println( str );
    And when I receive data I put something similar with string read with
    br.readLine().
    For unicode characters the result is different ( I use ascii and russian characters ). At sending data, it is normal, and at receiving I get '?' instead of unicode characters, something like this
    109 101 115 115 58 98 108 117 101 58 32 1092 1099
    before sending data and this
    109 101 115 115 58 98 108 117 101 58 32 63 63
    after receiving.
    Can somebody help me with this, or it is a bug?

    Ok, I just solved it. I had to create reader and writer like this:
    pw = new PrintWriter( new OutputStreamWriter( skt.getOutputStream(), "UTF-16" ) );
    br = new BufferedReader( new InputStreamReader( skt.getInputStream(), "UTF-16" ) );
    Seems that default encoding set was not unicode even if it is Writer and Reader!

  • How to store a data on txt file through java program

    that means i want a coding for write data on txt file using java program.that storing data is stored like this formate,
    sathees
    krishnan
    rama
    suresh
    Stored on one by one. not like this
    sathees krishnan rama suresh.........

    import java.io.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class rsk1{
    public static void main (String argv []){
    try {
    String sr[] = new String[100];
                   String s1=" ";
                   int j=0;
                   DataInputStream in = new DataInputStream(System.in);
                   OutputStream f1 = new FileOutputStream("file1.txt");
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("book.xml"));
    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " +
    doc.getDocumentElement().getNodeName());
    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);
    for(int s=0; s<listOfPersons.getLength() ; s++){
    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
    Element firstPersonElement = (Element)firstPersonNode;
    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
    Element firstNameElement = (Element)firstNameList.item(0);
    NodeList textFNList = firstNameElement.getChildNodes();
    sr[++j]=((Node)textFNList.item(0)).getNodeValue().trim();
    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
    Element lastNameElement = (Element)lastNameList.item(0);
    NodeList textLNList = lastNameElement.getChildNodes();
    sr[++j]=((Node)textLNList.item(0)).getNodeValue().trim();
    NodeList ageList = firstPersonElement.getElementsByTagName("age");
    Element ageElement = (Element)ageList.item(0);
    NodeList textAgeList = ageElement.getChildNodes();
    sr[++j]=((Node)textAgeList.item(0)).getNodeValue().trim();
    NodeList stuList = firstPersonElement.getElementsByTagName("stu");
    Element stuElement = (Element)stuList.item(0);
    NodeList textstuList = stuElement.getChildNodes();
    sr[++j]=((Node)textstuList.item(0)).getNodeValue().trim();
    }//end of if clause
    }//end of for loop with s var
    System.out.println("Process completed");
    for(int i=1;i<=j;i++)
                   byte buf[] = sr.getBytes();
                                       byte buf1[] = s1.getBytes();
         f1.write(buf);
                                       f1.write(buf1);
    f1.close();
    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line "
    + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    }catch (Throwable t) {
    t.printStackTrace ();
    }//end of main

  • Updation in zip file through java program

    Hi,
    Can any buddy help me updating zip file using java programs. I dont want to delete the zip file but I want to update single file in the zip.
    Any clue ?
    Regards,
    Ashish

    I mean I want to update a zip file using java program.
    Suppose there are 4 files zipped into single zip file.
    zipped.zip contains a.txt, b.txt. c.txt. d.txt
    Now the contect of a.txt got changed and I want to update zipped.zip to with the changed a.txt.
    I have one way of creating a new file with new set of a.txt, b.txt, c.txt and then delete the earliar zipped.zip and rename the newly created zipped to zipped.zip.
    I dont want to do the same as above mentioned way. Is there any way provided in java API to remove any entry or update any entry?
    I feel now the problem has got explained in details.
    Any help ?

  • Printing through socket programming

    Hi,
    i have written a clent side socket program which connects to my printer.
    and print the byte[] input stream . I ran my prog and it didn't throw any exception/error. The connection was also made successfully however no page is being printed by the printer.
    Any suggestion over this issue?
    Code:-      public static void testPrint(byte[] b, InetAddress printerName, int port) throws IOException{          
              System.out.println("Inside Test method");
              System.out.println("PrinterName is" +printerName +"---"+"port is" +port +"----byte is " +b.toString());
              if (b!= null) {
                   Socket so = null;
                   OutputStream out = null;
                   try {
                        so = new Socket(printerName,port);               
                    if (!so.isConnected()) {
                       System.out.println(printerName + ": " + port + "Connect failed");
                    out = so.getOutputStream();                    
                        if(out != null) {
                             System.out.println("OutPut Stream is not null"+out);
                             out.write(b);
                             out.flush();
                        else {
                             System.out.println("OutPut Stream is null");
                   catch (UnknownHostException ue) {
                        System.out.println("Printer is not recognised" +ue);               
                   catch (IOException ioe) {
                        System.out.println("I/O error" +ioe);
                   finally {
                        try {
                             if (out != null) {                              
                                  out.close();
                        catch (IOException ioe) {
                             System.out.println("Unable to close output stream for connection : " + printerName + " : " + port);
                        try {
                             if (so != null) {
                                  System.out.println("Closing Socket Connection");
                                  so.close();
                        catch (IOException ioe) {
                             System.out.println("Unable to close socket connection : " + printerName + " : " + port);
              }

    Hi,
    i have written a clent side socket program which connects to my printer.
    and print the byte[] input stream . I ran my prog and it didn't throw any exception/error. The connection was also made successfully however no page is being printed by the printer.
    Any suggestion over this issue?
    Code:-      public static void testPrint(byte[] b, InetAddress printerName, int port) throws IOException{          
              System.out.println("Inside Test method");
              System.out.println("PrinterName is" +printerName +"---"+"port is" +port +"----byte is " +b.toString());
              if (b!= null) {
                   Socket so = null;
                   OutputStream out = null;
                   try {
                        so = new Socket(printerName,port);               
                    if (!so.isConnected()) {
                       System.out.println(printerName + ": " + port + "Connect failed");
                    out = so.getOutputStream();                    
                        if(out != null) {
                             System.out.println("OutPut Stream is not null"+out);
                             out.write(b);
                             out.flush();
                        else {
                             System.out.println("OutPut Stream is null");
                   catch (UnknownHostException ue) {
                        System.out.println("Printer is not recognised" +ue);               
                   catch (IOException ioe) {
                        System.out.println("I/O error" +ioe);
                   finally {
                        try {
                             if (out != null) {                              
                                  out.close();
                        catch (IOException ioe) {
                             System.out.println("Unable to close output stream for connection : " + printerName + " : " + port);
                        try {
                             if (so != null) {
                                  System.out.println("Closing Socket Connection");
                                  so.close();
                        catch (IOException ioe) {
                             System.out.println("Unable to close socket connection : " + printerName + " : " + port);
              }

  • Transfering files through sockets

    Hi
    I am still having difficulties making this work.
    I want to transfer a file (.exe, .zip) etc through a socket.
    I have created a fileinputstream to the file, and read in all its bytes.
    I then create an outputstream with the sockets output stream(socket is called incomming):
    FileInputStream fin = new FileInputStream("D:\\steve.txt");
    int size = fin.available();//for they byte array!
    System.out.println("Number of bytes in this file is " + size);
    byte b[] = new byte[size];//byte buffer holds the exact number of bytes the file contains!
    fin.read(b);
    OutputStream fileSender = incomming.getOutputStream();
                   fileSender.write(b, 0, size);
                   fileSender.close();
    I am positive the byte array holds all the bytes in the file as i have tested that.
    The problem is i dont seem to get anything out the client end. I pass along the file size and construct a byte array to hold it this is the client code:
    InputStream inFile = soc.getInputStream();
    populateTextArea("reading bytes!");
    byte b[] = new byte[inLineNum]; //inLIneNum is the correct size for sure
    inFile.read(b,0, inLineNum);
    FileOutputStream foutnew = new FileOutputStream("C:\\TEMP01\\STevenTESTtest.txt");
    foutnew.write(b);
    The resulting file contains nothing, all it contains is a load of ascii code (00).
    Any suggestions please, I'm probably missing something really dumb but I've spent about 5 hours and am totally fed up with it.
    Steve

    hehe it was working all the time, its just that my test files are large (typically over 5 meg) so its taking ages to transfer....So, does anyone know how to speed up a socket connection (if its even possible).
    Cheers
    Steve

  • Writing into a jar file through Java program

    Is there a way to get a file from a jar (for ex. a properties file) make changes to it on the fly and write the same file back to the jar through a Java program?

    I cannnot give u exact code as i am bit busy..but i am giving close to exact
    below is code for reading contents of jar file
    import java.io.*;
    import java.util.jar.*;
    public class JarRead {
    public static void main (String args[])
    throws IOException {
    if (args.length != 2) {
    System.out.println(
    "Please provide a JAR filename and file to read");
    System.exit(-1);
    JarFile jarFile = new JarFile(args[0]);
    JarEntry entry = jarFile.getJarEntry(args[1]);
    InputStream input = jarFile.getInputStream(entry);
    process(input);
    jarFile.close();
    private static void process(InputStream input)
    throws IOException {
    InputStreamReader isr =
    new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    while ((line = reader.readLine()) != null) {
    System.out.println(line);
    reader.close();
    now here say u have test.jar which contains test.txt (file)
    then
    java JarRead test.jar test.txt
    will print content of text.txt
    now in ur case u write content of each file in some other file modify it there and then create a jar file from those files using jaroutput stream .....
    this may not be all clear ..but what to do..bit busy...u are welcomed to make changes in above stratergy....n queries if any after using above stratergy and/or your great brain...

  • Create CSV file through a program in background

    Hello everyone!
    I'm facing a problem using class CL_GUI_FRONTEND_SERVICES to generate a csv file.
    I have a report in SCM that will export data from APO to some csv files.
    At this moment I'm using GUI_DOWNLOAD method, it works perfectly! The problem is that this program is supposed to run in a background job, and as far as I read and searched for it.. GUI_DOWNLOAD and GUI_UPLOAD are not supposed to run in bakcground because of a "client-server" problem... well.. ok...
    So... I tried with the "OPEN DATASET" and it worked fine also, but now comes another issue: the "open dataset" method only writes/reads files located in the system server(is that right?)... and my file will be located on another location in the intranet.
    What should I use to generate this csv files in a background job!?
    Thanks,
    Martin

    there isn't a "client-server" problem...background jobs have no connectivity to a gui/presentation server and therefore no ability to upload/download to a desktop target....
    You can save, as noted, to any server visible to the SAP instance you're executing on.  I would recommend that you look at a multi-step process....
    create your internal table
    store that internal table in a file on your apps server (comma-delimited is okay, but tab-delimited would be much better choice)
    if you need to place the file where another system can access,
    utilize FTP capability in SAP to "copy" or "send" that file to an FTP target, after you have successfully written the file to the APPS server.
    If the file can be retrieved by a SAP user,
    write or utilize an existing piece of code to grab the file, upload into SAP and then utilize GUI_DOWNLOAD to transfer to the user's desktop target.
    This allows you to have both a background process, but have the file accessible to an SAP user after the file has been created.  I have several processes that do this and retrieval by the user is both easy and convenient, since the user is notified by my background job that the file has been created, etc.

  • Invoking exe file through java program

    I have one exe file,which i want to invoke it from java program.I have used Runtime class to execute the exe, but it throws an exception
    java.io.IOException: CreateProcess: afp2web.exe -q -PDF -c -fm samples\medform.a
    fp error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at Afp2PdfDemo.main(Afp2PdfDemo.java:7)
    However if i give the absolute path of exe file then it doesn't throw an exception but at the same time,it doesn't the do the expected job.
    Can somebody throw some light on this?
    Thanx in advance
    Regards,
    Pulak

    Have you tried also supplying the absolute paths of the file arguments like "samples\medform.a"?

  • Open Multiple Port through Socket Programming

    Hi,
    Actually I want to connect to three diff. ports on a Server from clinet, the port should be identified by a particular number.... and multiple users can access the server a the same time.... how do I program it....
    I need to program Client side....
    Thanks
    Sharad

    The client will need to be multithreaded if you want to connect to more then one port at a time from the client.
    public class Client {
    int port;
    String addr;
    ... openConnection(addr,port);
    the openConnection(String, int) method will actaully need to open a new thread where all the actual code goes. This will allow the Client class to call openConnection() again and use a new server/port. And you can keep calling this until you don't have any more local ports to bind to, or the server runs out of ports, or both.
    The book Core Java 2, volumes 1 and 2 have good examples of this and I also suggest Java Network Programming and Distributed Computing.

  • File thansfer through socket problem

    i am writing server /client program, where the server wait for client request to send or receive file through socket.
    can i use 1 socket to handle the request (client want to send or download file) and file data transfer?
    if yes, how to handle the beginging of file transfer after receive a request?
    and how can server know when the file transfer is completed?

    This tutorial should help:
    http://java.sun.com/docs/books/tutorial/networking/index.html

Maybe you are looking for

  • I am very upset with both Iphone 3G and 2.0 software

    OK These are my gripes First the actual store experience, it was a zoo. I waited in line for 2 hours and I did not even get an apology from the people at the store. They just told me it was AT&T's fault and to complain to them. It took them 25 minute

  • User Exit for PO (Purchase Order) Change

    Hi, I want to know the SAP Standard User Exit that is triggered ONLY during changing / modification of PO(Purchase Order). Thanks in Advance. RK

  • Issue Regarding ALV List Report

    Hi, I have prepared a ALV List report. I have made use of <b>REUSE_ALV_LIST_DISPLAY</b>. I have put a <b>check box</b> in the output at the begining of every Record. Now what i want is to put a <b>SELECT ALL</b> & <b>DESELECT ALL Buttons</b> on Appli

  • Printing spreads question.

    Hi all, As an exercise, I copied my 11x17 folded brochure file and reformatted it into a 4 page 8.5x11 document to test some printing options. I want to print pages 1 and 4, the front and back outside pages, together on a single 11x17 sheet. I select

  • Home pages opens hidden by another open application. How do I fix this problem?

    If I am running any application - MS Office, iTunes, Photoshop, when I click the shortcut to open Firefox, the homepage is not displayed, but is hidden behind the open aps. This is a new glitch and I need to correct it so opening the homepage follows