Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Passing a file part to a socket?

807580Aug 25 2010 — edited Sep 2 2010
Hi!

I am working on passing a file between 'stations'. I've got the sending part from one station to another down pat. But what I want to do next is to try and 'stream' the file so that while a station is receiving the file then that station is passing what it receives to another station.

Example: Station A -> Station B -> Station C. Station A sends a file to Station B. Station B receives the file in parts ( I am using 1024 bytes as my buffer size ). It should be that when Station B reads a part from the InputStream, it sends that part into its connection with Station C. However, my problem is that the file that results always results in it being corrupted.

Here is the code that I use:

When receiving from InputStream and converting to file:
private static void toFile(InputStream ins, FileOutputStream fos, int len, int buf_size, OutputStream os,FileOutputStream fos2) throws
        java.io.FileNotFoundException,
        java.io.IOException {

    byte[] buffer = new byte[buf_size];

    int       len_read=0;
    int total_len_read=0;

    while ( total_len_read + buf_size <= len) {
      len_read = ins.read(buffer);
      total_len_read += len_read;
      ByteStream.toStream(os, "%"+buf_size); //This is the part where I send a message signifying that I am sending a part and its buffer size
      ByteStream.toStream(os, len_read); //This is the part where I am sending the part (len_read) from the InputStream that I want to send to the Station C when I receive it
      fos.write(buffer, 0, len_read);
    }

    if (total_len_read < len) {
      toFile(ins, fos, len-total_len_read, buf_size/2);
    }
  }
And the part where I am receiving the message and part:
FileOutputStream fos = new FileOutputStream(new File("D:\\Song.mp3"));
str = ByteStream.toString(in); //this just gets the message from the InputStream

if (str.charAt(0) == '%')
{
        int buf_size = Integer.parseInt(str.split("%")[1]);
        byte[] buffer = new byte[buf_size];
        int len_read = bs.toInt(in);
        ByteStream.WriteToFile(buffer, len_read, fos);
}

.
.
.

public static void WriteToFile(byte[] buffer, int len_read, FileOutputStream fos)
  {
      try{
        fos.write(buffer, 0, len_read);
      }
      catch(Exception e)
      {}
  }
I think one of the main problems is that when I send the len_read variable through the socket, it loses its data. Are there other ways on how to work around this?

Thank you! If you need additional details, feel free to let me know!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 30 2010
Added on Aug 25 2010
19 comments
124 views