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

Similar Messages

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

  • Is it possible to store a back up on external HD by transfering files using Target Disk Mode?

    Dear Apple community,
    There's absolutely no way that I'm going to be able to fix my MBP without a clean install. I simply cannot log in and get to my desktop screen after upgrading to Mavericks. So I will have to erase everything and perform a clean install. However, before proceeding with this plan, I'll have to back up my files from my MPB since I cannot use my mac normally, I'll have to back up my files using the Target Disk Mode. I've connected my MPB to another MPB in the past, so I know how the process work. But this time around I won't be able to use another MBP but a MB. I have a few doubts regarding the process especially in what concernd adding an external HD to this equation. So please bear with me and see if you can answer my doubts.
    So this is the equipment I'll be working with: my MPB, my friends MacBook (2008) and my 1TB external hard drive.
    My basic question is: once I connect my MPB in Target Disk Mode to the MB, I'm sure I'd be able to transfer my files to this MB. But let's say that I don't want to leave my files in this MB (after all it's not my computer) and want to send my files straight to an external HD connected to this MB. Is it possible?  If positive, I know that the only FireWire port in the MB is a 400 port. That means my MBP will be connect to the MB using the only FireWire port available in the MB. So I believe that my external HD would have to be connected to the MB with the help of an USB cable. I assume that this will make the transferring process a little slower than if I could count solely on FireWire ports. Slowing the process down is not a problem but could this corrupt any of my files during the transferring process or even damage anything? I assume that would never happen after all it's just digital data, but better safe than sorry, right? What do you think?
    Another thought that occurred to me is: let's say I connect my MBP to the MB using the FireWire 400. I'd still have an FireWire 800 port available on my MBP. If I connect my external HD to my MBP (yeah, the one that will be in Target Disk Mode) using that FW 800 port, would my MBP allow this external HD to mount as if it was just another folder/drive in my computer? If positive, theoretically I'd be able to transfer files from my MBP to my external HD manually (by dragging files from folder to folders), right?
    I really don't want to transfer my files from the MBP to the MB and then from MB to external HD. That would just take time and I really don't know how much available space I'll find on my friend's MB.
    Oh, one last question: when transferring files using Target Disk Mode, do all computers involved in this process gotta have the same OS X version installed or it doesn't matter if e.g one is running Snow Leopard and the other Mavericks?
    Looking forward to hear back from you, experts.

    Grant Bennet-Alder West of Boston, USA 
    A new 1TB External drive (suitable to replace your current Internal drive if you choose to) and enclosure can be had for under US$160
    Ehh, you meant $60 ,  not $160
    CassHeger 
    I do need to buy an external HD to be used solely for that purpose.
    Yes, quality HD are cheap as dirt.
    however a likewise Toshiba Internal HD 1TB is $70   (same as used by Apple)
    http://www.ebay.com/itm/TOSHIBA-MQ01ABD100-1TB-5400-RPM-8MB-Cache-2-5-SATA-3-0Gb   -s-Internal-Notebook-/121107538930?pt=US_Internal_Hard_Disk_Drives&hash=item1c3 2 9263f2
    best options for the price, and high quality HD:
    Quality 1TB drives are $50 per TB on 3.5" or  $65 per TB on 2.5"
    Perfect 1TB for $68
    http://www.amazon.com/Toshiba-Canvio-Portable-Hard-Drive/dp/B005J7YA3W/ref=sr_1_ 1?ie=UTF8&qid=1379452568&sr=8-1&keywords=1tb+toshiba
    Nice 500gig for $50. ultraslim and perfect
    http://www.amazon.com/Toshiba-Canvio-Portable-External-Drive/dp/B009F1CXI2/ref=s r_1_1?s=electronics&ie=UTF8&qid=1377642728&sr=1-1&keywords=toshiba+slim+500gb
    2.5" USB portable High quality BEST FOR THE COST, Toshiba "tiny giant" 2TB drive (have several of them, LOT of storage in a SMALL package)    $117
    http://www.amazon.com/Toshiba-Canvio-Connect-Portable-HDTC720XK3C1/dp/B00CGUMS48 /ref=sr_1_4?s=electronics&ie=UTF8&qid=1379182740&sr=1-4&keywords=2tb+toshiba
    *This one is the BEST portable  external HD available that money can buy:
    HGST Touro Mobile 1TB USB 3.0 External Hard Drive  
    $88
    http://www.amazon.com/HGST-Mobile-Portable-External-0S03559/dp/B009GE6JI8/ref=sr _1_1?ie=UTF8&qid=1383238934&sr=8-1&keywords=HGST+Touro+Mobile+Pro+1TB+USB+3.0+72 00+RPM
    Most storage experts agree on the Hitachi 2.5"

  • Downloading a binary file using sockets without length known

    Hi all,
    I'm trying to download a binary(.exe) file using socket, where the length of the file is not known. Please take a look at the code I'm using:
          var readBin = socketBin.read();
         <-- Here comes the code that checks for http Content-length header field
         ; If content-length field is available, then I'll use it to download file, else proceed with following code -->
        pBar.reset("Downloading plugin..",null);pBar.hit(readBin.length);       
                while (1)
                    binFil.write(readBin);     //'binFil' is the file, into which downloaded file is written.
                    readBin = socketBin.read();
                    pBar.hit(readBin.length);
                    if( socketBin.eof || readBin.length<=0){
                        break;}          
                binFil.write(readBin);
                binFil.close();
                socketBin.close();
    Problem is: I'm able to download file within 10 seconds when content-length is known. But when content-length is not known, its taking about 1 and half minute to download, also the progress bar gets struck for much of time.
    FYI: socket is opened in binary mode, file is getting downloaded correctly(even though it takes abt a minute). BTW Im using CS5.5 extendscript
    I'm not able to figure out where the bug is.

    Hi, Srikanth:
    Sevaral points.
    #1 When posting code, please use the web interface and the >> icon and choose Syntax Highlighting >> Java. Otherwise your code is just too hard to read and gets misformatted.
    #2 Apropos of #1, your script as written does not work, because this line:
    url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$ 1/$2/$3/$4");
    has an extra space in the $1 and should be this:
    url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$1/$2/$3/$4");
    Please take an extra moment to make sure that when you asking for help, you do so in a way that makes sense. Otherwise it takes too much effort to help you, and that is frustrating.
    #3 If we instrument your script by adding a line to the while() loop:
                while (1)
                    binFil.write(readBin);
                    readBin = socketBin.read();
                    $.writeln(Date()+" Read "+readBin.length+" chars, eof is "+socketBin.eof);
                    if(  readBin.length<=0){         break;}              
    We get output like this:
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 631 chars, eof is false
    Mon Jul 11 2011 12:07:06 GMT-0400 Read 0 chars, eof is false
    Result: undefined
    Therefore, we can reasonably conclude that the last read at the end of the data stream returns a short read when the other side blocks.
    Unfortunately, that's clearly insufficient since you can get short reads all the time.
    I'm not sure why you say the length of the file is not known, HTTP provides it to you in the Content-Length field of the response.
    But the easy answer is to get the server to close it for you. This is easy, enough, with Connection: close. Why were you specifying
    Connection: keep-alive, anyhow?:
                var requestBin =
                "GET /" + parsedURLBin.path + " HTTP/1.1\n" +
                "Host: " + parsedURLBin.address + "\n" +
                "User-Agent: InDesign ExtendScript\n" +
                "Accept: */*\n" +
                //"Connection: keep-alive\n\n";
                "Connection: close\n"+
                "\n";
    This yields a nice tidy:
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 735 chars, eof is true
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 0 chars, eof is true
    I suspect you're also better off using something like socketBin.read(64*1024) for a 64k buffer size, but it doesn't seem to effect the on-the-wire protocol, so perhaps its not so important.
    If you don't want to reply on the server

  • Transfering files using drag and drop to Nano P

    I havent installed the supplied disks that came with my Nano Plus but am transfering files using drag and drop from "my music" folder on my computer to the Nano. These files are stored on my computer as the Name of the Artist as the folder name with a sub folder named the CD title (default setting when using Windows media to rip) with the individual track files in that folder.
    When I drag the main folder over to my Nano it just displays the Album title on the screen but not by artist and there is no way to select by artist (you can just switch "folders" on the Nano which will then display the CD title. If I used the supplied software with my Nano to transfer the files will I be able to choose by artist, CD, Genre, etc or is this not a function of the Nano?
    Is it best to just select the individual song tracks and throw them in one large group on the Nano and then it can figure out which artist, album, genre they belong to?

    The player will only show directories that contain music files.
    The behaviour you want is common on players that manage their content with a database (typically HD-based devices), but Creative's flash players don't work that way (and the software used on the host computer doesn't have any influence on this - the user interface is controlled by the player's firmware).

  • Send a picture file using sockets

    Hi,
    Could someone please tell me how I can send a picture file using sockets across a TCP/IP network? I have managed to do it by converting the file into a byte array and then sending it but I dont see the data back at the client when I recieve the file. I just see the byte array as having size 0 at client.
    Byte array size is correct at client side.
    //client code
    System.out.println("Authenticating client");
              localServer = InetAddress.getLocalHost();
              AuthConnection = new Socket(localServer,8189);
              out = new PrintWriter(AuthConnection.getOutputStream());
              InputStream is = AuthConnection.getInputStream();
              System.out.println(is.available());
              byte[] store = new byte[is.available()];
              is.read(store);
         ImageIcon image = new ImageIcon(store);
              JLabel background = new JLabel(image);
              background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
              getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
    //extra code here
              catch (UnknownHostException e) {
    System.err.println("Don't know about host: LocalHost");
    System.exit(1);
              catch (IOException e) {
    System.err.println("Couldn't get I/O for "
    + "the connection to: LocalHost");
    System.exit(1);
    //server code
                   DataOutputStream out = new DataOutputStream(incoming.getOutputStream());
                   FileInputStream fin = new FileInputStream("3trees.gif");
                   byte[] b = new byte[fin.available()];
                   int ret = fin.read(b);
                   out.write(b);

    i used OutputStream as
    OutputStream out = incoming.getOutputStream(); and flushed the stream too.
    But I still get the same output on the client side. I tried sending a string and it works , but I cant seem to be able to populate the byte array on the client side. It keeps showing zero. Please advise.
    Thank you.

  • Moving Files using sockets

    I wanted to know of a good way to move, not copy, files using sockets? Any help would be great.
    Thanks

    Even on the same machine, you can only move a file on the same filesystem. i.e. the file appears in a different directory rather than copying the file.
    If you have an C: and D: drive for example it will copy and delete the file on a move.
    Unix allows you to have symbolic links which can make a file/directory from anywhere appear anywhere on your filesystem. It does not copy or actaully move the file, it just appears to be where ever you choose.

  • Reading / Writing files using Sockets

    Hi there guys,
    I am fairly new to this forum. I have been having a problem for the past three days. I am implementing a client/server implementation using Sockets which is a submodule of a project I am working on. What I want is that a files content are read and transferred over the network to the server that writes it down to a different file .
    What the code presently does is :
    <<<<Client Code >>>>
    It reads a file input.txt and sends the content over the network to the server.
    <<<< Server Code >>>
    It reads the incoming data from the client and writes the data out to a file called output.txt
    What I want now is that the server should read the file output.txt and send the contents to the client which reads it and then writes it down as a new file called serverouput.txt . After that I want to compare and see of the size of input.txt and serveroutput.txt . If both are same that means that data has been written reliably to the server.
    I have been trying to implement it for a long time and nothing seems to work out. I am posting the code for both client and server below. Any help in finalising things would be really appreciated.
    CLIENT CODE
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Date;
    import java.io.*;
    import java.net.*;
    class sc {
    static final int PORT = 4444;          //Change this to the relevant port
    static final String HOST = "127.0.0.1";
         //Change this to the relevant HOST,
    //(where Server.java is running)
    public static void main(String args[]) {
    try {
    System.out.print("Sending data...\n");
    Socket skt = new Socket(HOST, PORT);
                   // Set the socket option just in case server stalls
    skt.setSoTimeout ( 2000 );
                   skt.setSoKeepAlive(true);
    //Create a file input stream and a buffered input stream.
    FileInputStream fis = new FileInputStream("input.txt");
    BufferedInputStream in = new BufferedInputStream(fis);
    BufferedOutputStream out = new BufferedOutputStream( skt.getOutputStream() );
    //Read, and write the file to the socket
    int i;
    while ((i = in.read()) != -1) {
    out.write(i);
    //System.out.println(i);
                   // Enable SO_KEEPALIVE
    out.flush();
    out.close();
    in.close();
    skt.close();
    catch( Exception e ) {
    System.out.print("Error! It didn't work! " + e + "\n");
              catch( IOException e ) {
    System.out.print("Error! It didn't work! " + e + "\n");
    SERVER CODE
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Date;
    import java.io.*;
    import java.net.*;
    class ClientWorker implements Runnable {
    private Socket client;
    ClientWorker(Socket client) {
    this.client = client;
    public void run(){
    try      {
    FileOutputStream fos = new FileOutputStream("output.txt");
    BufferedOutputStream out = new BufferedOutputStream(fos);
    BufferedInputStream in = new BufferedInputStream( client.getInputStream() );
    //Read, and write the file to the socket
    int i;
    while ((i = in.read()) != -1) {
    out.write(i);
    //System.out.println(i);
    System.out.println("Receiving data...");
    out.flush();
    in.close();
    out.close();
    client.close();
    // srvr.close();
    System.out.println("Transfer complete.");
    catch(Exception e) {
    System.out.print("Error! It didn't work! " + e + "\n");
    class ss1 {
    ServerSocket server = null;
    ss1(){ //Begin Constructor
    } //End Constructor
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    while(true){
    ClientWorker w;
    try{
    w = new ClientWorker(server.accept());
    Thread t = new Thread(w);
    t.start();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    protected void finalize(){
    //Objects created in run method are finalized when
    //program terminates and thread exits
    try{
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close socket");
    System.exit(-1);
    public static void main(String[] args){
    ss1 frame = new ss1();
         frame.listenSocket();
    }

    ............................................. After that I want to
    compare and see of the size of input.txt and
    serveroutput.txt . If both are same that means that
    data has been written reliably to the server.You don't need to do this. TCP/IP ensures the reliable transmition of data. By using a socket you are automaticaly sure that the data is reliably transmitted (Unless there is some sort of exception).
    To get the size of the files you can use a File object. Look it up in java.io package in API documentation.
    java-code-snippet (without error checking)
    File clientFile = new File("input.txt");
    clientFile.length();

  • How to Transfer files using socket remote method invocation?

    hello guys,
    i am working on java sockets...and i need to send and receive files though Java RMI. how will i go with it....
    Please do help me in this regard
    Edited by: sandeep_genevsoftech on Apr 4, 2008 4:32 AM

    I am also developing a similar application of file transfer but using sockets in place of RMI.The file gets transfered if i run client and server on same m/c(as localhost),but shows "access denied" if run on different m/c.I suppose some security policies need to be set.Can anybody help?

  • Sending file using sockets (difficult)

    Hi, i have the following section of code
    (of which i am not claiming ownership) which
    implements a DCC Send command from irc.
    It accomplishes this using sockets, and while
    i understand how the code accomplishes what it
    does, i need help with a possible modification.
    Basically what i am looking to do is keep track
    of the progress of the send - so that the
    user can at any time see how much of the file
    has been sent and how much is remaining.
    If anyone has done such a thing in the past or
    has a good idea as to how this should be implemented,
    i would be greatful for their help.
    Here is the code:
    new Thread() {
                public void run() {
                    try {
                        ServerSocket ss = new ServerSocket(0);
                        ss.setSoTimeout(timeout);
                        int port = ss.getLocalPort();
                        //byte[] ip = ss.getInetAddress().getAddress();
                        byte[] ip = InetAddress.getLocalHost().getAddress();
                        long ipNum = 0;
                        long multiplier = 1;
                        for (int i = 3; i >= 0; i--) {
                            int byteVal = (ip[i] + 256) % 256;
                            ipNum += byteVal*multiplier;
                            multiplier *= 256;
                        // Rename the filename so it has no whitespace in it when we send it.
                        // .... I really should do this a bit more nicely at some point ....
                        String safeFilename = file.getName().replace(' ', '_');
                        safeFilename = safeFilename.replace('\t', '_');
                        // Send the message to the user, telling them where to connect to in order to get the file.
                        sendCTCPCommand(nick, "DCC SEND " + safeFilename + " " + ipNum + " " + port + " " + file.length());
                        // The client may now connect to us and download the file.
                        Socket socket = ss.accept();
                        socket.setSoTimeout(30000);
                        // Might as well close the server socket now; it's finished with.
                        ss.close();
                        BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
                        BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
                        BufferedInputStream finput = new BufferedInputStream(new FileInputStream(file));
                        byte[] outBuffer = new byte[bufferSize];
                        byte[] inBuffer = new byte[4];
                        int bytesRead = 0;
                        while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
                            output.write(outBuffer, 0, bytesRead);
                            output.flush();
                            input.read(inBuffer, 0, inBuffer.length);
                        output.close();
                        input.close();
                        log("+++ DCC SEND Completed to " + nick + " (" + file.getPath() + ")");
                    }

    You already have the necessary code to find the number of bytes sent at any point during the transmission. You can find out the size of the file by instantiating a RandomAccessFile before you send it, and querying for the file length.
    I suggest you make the file size and bytes sent volatile and conveniently accessible to another thread (best implemented here as an inner class?). Your new thread will need to monitor the file transfer at intervals to update the progress indicator. You can generate estimates of time remaining by measuring the average transmission rate, and extrapolating using the total file size. Classically this is done using an average, but you might be better just maintaining a list of fairly recent samples, allowing for the speed swings inherent in internet connections.
    How you update the progress indicator from your monitor thread is up to you. I suggest exposing methods in the UI for setting the progress and time remaining, and simply update them from the monitor.
    Does this help any?

  • Error transferring files using MicroPhoto Media Explo

    Hello, I'm having a very frustrating issue. I just had the hard dri've replaced on my MicroPhoto 8, and now when I try to add files using MicroPhoto Media Explorer (as I have for the last 8 months), I get the message "files not transferred; unknown error."? Likewise, when I try to use that same software to rip a cd directly to the player, it acts like it's working, then I get an error message. I know there are other ways to accomplish this, but since I'm starting from scratch, I'd rather use the method that I find to be the fastest and that I'm most familiar with. I've reloaded the software onto my PC, I've rebooted, reformatted, and updated the firmware on the player. Has anyone had this problem, or have any suggestions? Thanks!

    Error which pops up : "The destination you have specified does not exist. Might be an offline network location or empty cd or dvd drive. Check location and try again"

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

  • Transfering Files Using Windows Explorer

    Rather than using windows media player, why can't I just use windows explorer to add photos to my droid 2?  When I hook up my droid 2 to my computer with the usb cable, the droid appears in windows explorer.  I want to just drag and drop photos to the droid.  I have tried this with a couple of photos and it seems to work.  Will this method cause any problems?  It seems a lot easier than using windows media player to "sync" files.

    It apeaqrs that they automatically go into the photo folder.  I was able to access them via the "Gallery" app.
    I wonder why the user guide doesn't recommend this since I find it a lot easier to do than using the "sync" process?

  • HOW TO TRANSFER FILE USING SOCKET

    HI....
    My project is backup sever
    I want to take backup of any number of file and of any size please tell
    me solution how i can do this for this i done the zip file of backup.
    I done this but i face some problem...
    regards
    Ahire sharad

    ahire, if what you want is to transfer a file over a socket here's an example of a sender. If you need the reciever code too, let me know.
    public void run()
              FileInputStream inFile = null;
              try
                   Boolean done = false;
                   int inByte;
                   inFile = new FileInputStream(filename);
                   byte[] byteBuffer = new byte[128000];
                   while(!done)
                        inByte = inFile.read(byteBuffer, 0, byteBuffer.length);                         
                        if (inByte == -1)
                             done = true;
                        else
                             out.write(byteBuffer, 0, inByte);
                   inFile.close();
              catch (Exception e)
                   try {inFile.close();}
                   catch (Exception ex) {ex.printStackTrace();}
                   try{Thread.sleep(10);}catch(Exception ex){}
                   JOptionPane.showMessageDialog(null,"Error sending file " + filename + "\nError: " + e.toString(),"Error", JOptionPane.ERROR_MESSAGE);
         }Pd: As I see your english isn't so good... I can help you in spanish or italian too... just let me know. Regards,
    Message was edited by:
    doy2001

  • 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

Maybe you are looking for

  • AP 1200 Just goes down hard

    We have a 1200 Aironet just go down hard for no reason through out the day, we replaced the Power Injector with a C2960 POE Switch, we also replaced the cabiling. When it goes down hard all three lights are still green as if the AP is still up. We ve

  • Sonata and last.fm

    Hello, when I start sonata in console, I get: Error authenticating audioscrobbler AudioScrobblerHandshakeError: The timestamp provided was not close enough to the current time.

  • Combining CS4 installation sources

    A lot of the CS4 components are identical across different products. Can I combine, say, the Photoshop and Illustrator install sources into a single directory to save disk space on my deployment server? I am preparing an AdobeUberInstaller.exe for ea

  • Run OMBPlus script in JDeveloper

    Hello, I've installed OMB Plus in Oracle9i Jdeveloper 9.0.3.1 using "Oracle9i Warehouse Builder Scripting Reference" (Chapter "Running OMB Plus in Oracle9i JDeveloper). All work fine (OMBPlus console, OMB Plus menu options,...), but when I try to run

  • Can't select alternate outputs

    Years ago, I ran a Logic Version called RPC-Pro on windows in tandem with Rolands' SI24 interface. I recently purchased an iMac and have installed Logic Pro 9. My old projects (.LSO files) from RPC-Pro load just fine in Logic 9, everything is intact