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

Similar Messages

  • 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.

  • Transfering files via sockets

    Hi
    I am writing a client server app, and am communicating between the clients and server using the Socket and Serversocket class's. Transfering strings is very easy, but i also want to transfer files. I usually use Fileinputstream/fileoutputstream in normal circumstances, but i dont think this will work with sockets.
    Any suggestions on how i can transfer files through a sockets would be most welcome.
    Cheers
    Steve

    Just create the InputStream to your file, read in some bytes, write the bytes to the sockets OutputStream, voila!
    Rob.

  • 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

  • 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

  • Transfering Files using Sockets

    Hello, im new to Java network. Im trying to build a client-server application that reads a file, converts it to bytes and writes it to socket. A server application then gets the bytes, and writes the file to the remote location.
    It seems whatever i do results to errors.
    Any ideas what might be the fault?
    Regards
    Client
    ========
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class DataHandler {
         static Socket toServer;
         static byte[] bytes;
         static DataOutputStream out;
         public DataHandler(byte[] bytesReturned) {
              bytes = bytesReturned;
         public static void performActions(File fileGiven) throws IOException {
              try {
                   System.out.println("class CH");
                   toServer = new Socket("localhost", 18583);
                   readInput(fileGiven);
                   sendData();
              catch (UnknownHostException ex) {
                   System.err.println(ex);
              catch (IOException ex) {
                   System.err.println(ex);
              finally{
                   closeConnection();
         private static void closeConnection() throws IOException {
              out.close();
              toServer.close();
         public static byte[] readInput(File file) throws IOException {
              InputStream is = new FileInputStream(file);
              // Get the size of the file
              long length = file.length();
              if (length > Integer.MAX_VALUE) {
                   // File is too large
              // Create the byte array to hold the data
              bytes = new byte[(int) length];
              // Read in the bytes
              int offset = 0;
              int numRead = 0;
              while (offset < bytes.length
                        && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                   offset += numRead;
              // Ensure all the bytes have been read in
              if (offset < bytes.length) {
                   throw new IOException("Could not completely read file "
                             + file.getName());
              // Close the input stream and return bytes
              is.close();
              System.out.println(bytes);
              return bytes;
         private static void sendData() throws IOException {
              out = new DataOutputStream(toServer.getOutputStream());
              out.write(bytes);
         public static void main (String args[]){
              File file = new File("test.pdf");
              try {
                   performActions(file);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    Server
    =======
    import java.io.DataInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Receiver {
         static ServerSocket server;
         static Socket connection;
         static DataInputStream input;
         public static void runServer() throws Exception{
              try {
                   server = new ServerSocket(18583);
                   while (true){
                        getStreams();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              finally{
                   server.close();
                   connection.close();
         private static void getStreams() throws Exception {
              connection = server.accept();
              input = new DataInputStream(connection.getInputStream());
              System.out.println(input);
              byte[] store = new byte[input.readByte()];
              input.read(store);*/
              FileOutputStream fos = new FileOutputStream("received.pdf");
              fos.write(input);
              fos.close();
         public static void main (String args[]){
              try {
                   runServer();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }

    Ah, thanks a lot for the replies.
    It appears that i had some kind of writing to file error in server code at: fos.write(input);
    Its been fixed now.
    Non the less thank you very much for bothering :-)
    A silly question though. How is it possible to retain filename and filetype when sending a file? i.e. instead of having a FileOutputStream writing to a predefined by a string File (i.e. File file = new File("a_picture.jpg");) being able to send any type of file and keep their current format and name?
    I assume you should first send a string with the file name but the BufferedInputStream i have at the server mixes up both String and actual file bytes.
    Excuse me for the long question
    Kind Regards
    Chris

  • Transferring files through java web service(for VB Client)

    Hi,
    I have a VBA client that needs to access a file on a server through a web service ? how do I go about this ? Use SAAJ ? Can I create a VBA client for SAAJ ?

    I don't anderstand your problem,
    With wich client-application do you acces to Web Service,
    Do you program the Server side of the web service ????
    Cl�ment

  • Read contents of file into outputstream and send through socket

    I have a file. Instead of transferring the whole file through socket to the destination, I will read the contents from the file (big or small file size) into outputstream and send them to the destination where the client will receive the data and directly display it....
    Can you suggest any efficient way/methods to achieve that?
    Thanks.

    I don' t understand what you think the difference is between those two techniques, but:
    int count;
    byte[] buffer = new byte[16384];
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count);
    out.close();
    in.close();

  • 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

  • Oracle BAM to monitor transfer of files using sockets

    Hi,
    We have two programs transferring files using sockets. We wanted BAM to monitor the transfer.
    Would you please suggest if this is achievable in BAM , and if so , any pointers to how we may go about implementing it .
    Cheers,
    Anant.

    You could generate success/failure/progress from your utility to JMS or call BAM webservices to populate BAM Data Objects. Reports could be built on top of that.

  • Transferring images through a socket

    Hi,
    i'm writing a simplified webserver which gets a request from a client, gets the content from the origin server and returns it to the client as it is (currently..)
    The problem is that the images i transfer are corrupted and i'm not sure why (i'm guessing something to do with asci/binary mode transfer) but i don't know what's the proper way to do this.
    Right now i'm using InputStreamReader wrapped by BufferedReader to read the content.
    Can someone please advice??
    Thanks!!
    Hesher.

    I'm trying to transfer image / binary data through sockets for some time now and cannot manage to do so. I've read multiple threads where users describe similar problems, but I somehow can't get it to work and I don't know why. What I'm trying to do:
    Server side:
    1. Get length of file and send to client
    2. Read image from file and send to client socket output stream
    Client side:
    1. Obtain length of file from server
    2. Read image from server socket input stream and save to file
    Step 1 works fine. The size of the file is transformed correctly. The next thing is that the server is transferring the byte data from the file to the outputstream and the client is transferring the byte data from the inputstream to another file. Here, I use a generic transfer method:
    * This method transfers binary data.
    * @param is The source of the data.
    * @param os The destination of the data.
    * @param len The length size/length of the data.
    * @throws IOException
    public static void transfer(InputStream is,
              OutputStream os,
              long len) throws IOException {
         // Initializing the buffer
         byte[] buf = new byte[1024];
         // Amount of bytes read in total
         long sent = 0;
         // Amount of bytes currently read
         int cur = 0;
         // Transfer data:
         while(                         // Stop when:
                   (sent<len) &&          // enough data is sent OR
                   ((cur=is.read(buf))!=-1)// end of stream is reached
              os.write(buf, 0, cur);          // send buffer to output stream
              os.flush();               // flush output stream
              sent += cur;               // increment count of bytes sent
    }The success rate is about 50%, meaning about half the output images are corrupted, the other half is fine. If this helps at all to diagnose the problem: The failure images always have the same size.
    Cheers and thanks in advance for any hints!

  • How to transfer a binary file through the socket?

    hi,
    i have a problem when I want to transfer a binary file through the socket. On the server side we write a program with C. On the client side with use java. The socket worked fine when we transfer some asci files. But failed when transfer the binary file. How to solve the problem? Can someone give me some advice? Thanks a lot.
    sincerely,
    zheng chuanbo

    i use streams to read the binary file. The problem is I don't know when the transfered stream finished. With text file I can recognize the end of the transfer by a special string, but how to deal with the end of a stream? should the server send an "EOF" or something else to the client to notify the end?

  • Sockets: can only send once file through

    Hi,
    I am using sockets to send text and files to a client on a Clio. I want to send multiple files through. However, only the first file goes through. The rest are never received (although they are uploaded). My question is:
    Why can not send anything through the socket (text or files) after the first file is sent?
    The fileSend() is on the server side, fileReceive is on the client side.
    public static void fileSend (Socket uploadSocket, String source) {
         try {
             InputStream inFile = new FileInputStream(source);
             InputStream in = new BufferedInputStream(inFile);
             OutputStream out = new BufferedOutputStream(uploadSocket.getOutputStream());
             System.out.println("Sending " + source + ".");
             int data;
             int bytes = 0;
             while ((data = in.read()) != -1) {
              bytes++;
              out.write(data);
             bytes++;
             out.write(data);
             if (in != null) in.close();
             if (out != null) out.flush();
             System.out.println("Upload complete: " + bytes + " Bytes!");
         catch (Exception e) {
             System.err.println("Couldn't upload " + source + ": " + e.getMessage());
       public static void fileReceive (Socket downloadSocket, String destination) {
         try {
             InputStream in = new BufferedInputStream(downloadSocket.getInputStream());
             OutputStream outFile = new FileOutputStream(destination);
             OutputStream out = new BufferedOutputStream(outFile);
             System.out.println("Downloading data to " + destination + ".");
             int data = in.read();
             int bytes = 0;
             while (data != -1) {
              bytes++;
              out.write(data);
              data = in.read();
             bytes++;
             if (out != null) {
              out.flush();
              out.close();
             outFile.close();
             System.out.println("Download complete: " + bytes + " Bytes!");
             in.skip(in.available());
         catch (Exception e) {
             System.err.println("Couldn't download " + destination + ": " + e.getMessage());
        }Thanks,
    Neetin

    I think its better to pass the outputstream to the filesend() method and inputstream to fileReceive() method
    something like this:
    OutputStream out = new BufferedOutputStream(uploadSocket.getOutputStream());
    public static void fileSend (OutputStream os, String source) {
      //write your file onto the output stream
    InputStream in = new BufferedInputStream(downloadSocket.getInputStream());
    public static void fileReceive (InputStream is) {
      //Read from the input stream
    }This should work.. Good luck

  • File reading through Sockets???

    Hello,
    My application has a server and it has to read a file that is sent by the client.. how can the server read a file sent by the client through sockets?????
    Edited by: s_coder on Feb 19, 2009 11:20 PM

    s_coder wrote:
    Yes i read it but there input is given from the client to the server through the standard input stream.... how can i transfer a file thru the standard input stream? and the accept it at the server side???Come on mate. You need to be able to add two and two on your own.
    WTF is a "standard input stream"? And why if you followed the tutorial can you not figure out how to send the data of a file through a socket?
    Either you didn't really read the tutorial or you're pretty darn hopeless. Why don't you try and really follow the tutorial, not just glance at each page but understand what it is saying. Then make an attempt to write your program and if you get stuck come back with your code. Be sure to use the code formatting tags when you show us your code.

  • Send many files through a socket without closing Buffered Streams?

    Hi,
    I have an application that sends/receives files through a socket. To do this, on the receiver side I have a BufferedInputStream from the socket, and a BufferedOutputStream to the file on disk.
    On the sender side I have the same thing in reverse.
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)
    therefore, how can I tell the receiver that it has reached the end of a file?
    Can you show me any examples that send/receive more than one file without closing any streams/sockets?

    Hi,
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)Its not if you want to continuosly listen to the particular port.. like those of server, you need to use ServerSocket.
    for sending multiple files the sender(Socket) can request the file to server (ServerSocket). read the contents(file name) and then return the file over same connection, then close the connection.
    For next file you need to request again, put it in loop that will be better.
    A quick Google gives me this.
    Regards,
    Santosh.

Maybe you are looking for

  • QT Pro does not export sound...

    Hi there, I just bought QT Pro to convert my camera movies (MPEG1 Muxed, 640x480) into a format supported by iDVD but without any success... When I click on the movie file they open and play with sound in QT but when I choose Export (to various forma

  • Can't remove video from iPhoto/iMovie'11

    Help! I have an old video that shows up everytime I start iMovie'11, and I don't seem to be able to get rid of it. It shows up under the iPhoto video Library, but it doesn't show up at all in iPhoto so I am unable to delete it. I managed to locate it

  • SUN Application Server 8 On Solaris

    Hi I tried to deploy the smart ticket 1.2 demo which comes with the Evaluation version of SUN One 8 "j2eesdk-1_4-dr-solaris-eval" Unfortunately it does not work The server log shows: "......com.sun.jdo.api.persistence.support.JDOFatalUserException: J

  • Filtering a list using multiple filters with Parameters, if one filter empty no results returned. How to fix?

    Hi All, I would assume this is a common problem.  I am a having problems using filters on SharePoint 2013 Lists on a custom site page. I am using the Filter (text, date, Choice) Web Parts, however due to the limitations of the filter web parts, I am

  • Can not print T/O

    Dear all I create D/O then the system generage T/O automatically but T/O ducument can not print  which  have already marked print immediately in configuration. why I have to use LT31 for printing T/O. Please  advise me how to do this. Remark I used o