Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6137909
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T17:47:07+00:00 2026-05-23T17:47:07+00:00

this afternoon I wrote this class whose aim is give a easy way to

  • 0

this afternoon I wrote this class whose aim is give a easy way to exchange send a file over TCP Socket.
The problem it that, despite the final file size is correct, the content in wrong: precisely the destination file is made of various copies of the first buffer sent over Socket.
My class is simple: it calculates Q and R based on buffer size and sends this number together original filename to the client. I used a byte array to send data over Socket.

package it.s4sytems.java;  
import java.io.*;  
import java.net.*;  

public class FileOverObjectStream
{
    private File file;
    private int bufferSize = 4*1024*1024; //4MB default, comunque è stabilito dal sender

    private static class Info implements Serializable
    {
        public String fileName;
        public long q;
        public int r;
        public int bufferSize;
    }

    public FileOverObjectStream(File file)
    {
        this.file = file;
    }

    public FileOverObjectStream(File file, int bufferSize)
    {
        this(file);
        this.bufferSize = bufferSize;
    }

    public void sendFile(Socket socket) throws IOException
    {
        socket.getInputStream();
        sendFile( socket.getOutputStream() );
    }

    public void sendFile(OutputStream outStream)throws IOException
    {
        sendFile( new ObjectOutputStream(outStream) );
    }

    public void sendFile(ObjectOutputStream objOutStream) throws IOException
    {
        BufferedInputStream in = new BufferedInputStream( new FileInputStream(file) );
        byte[] buffer = new byte[bufferSize];

        Info info = new Info();
            info.fileName = file.getName();
            info.bufferSize = bufferSize;
            info.q = file.length() / bufferSize;
            info.r = (int) file.length() % bufferSize;
        objOutStream.writeObject(info);

        for(long i=0; i<info.q; i++)
        {
            in.read(buffer);
            objOutStream.writeObject(buffer);
            objOutStream.flush();
        }
        in.read( buffer = new byte[info.r]);
        objOutStream.writeObject(buffer);

        objOutStream.flush();
        in.close();
    }

    public String receiveFile(Socket socket) throws IOException, ClassNotFoundException
    {
        socket.getOutputStream();
        return receiveFile( socket.getInputStream() );
    }

    public String receiveFile(InputStream inStream) throws IOException, ClassNotFoundException
    {
        return receiveFile( new ObjectInputStream(inStream) );
    }

    public String receiveFile(ObjectInputStream objInStream) throws IOException, ClassNotFoundException
    {
        BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(file) );

        Info info = (Info) objInStream.readObject();
        for(long i=0; i<info.q+1; i++)
        {
            byte[] buffer = (byte[]) objInStream.readObject();
            out.write( buffer );
        }

        out.close();
        return info.fileName;
    }
}

I created two classes to make some try…

import it.s4sytems.java.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{
    public static void main(String arg[]) throws IOException
    {
        ServerSocket ss = new ServerSocket(18000);

        while(true)
        {
            Socket s = ss.accept();

            File file = new File("G:\\HCHCK_72_5.38.part04.rar");
            FileOverObjectStream sender = new FileOverObjectStream(file);
            sender.sendFile(s);
            s.close();
        }
    }
}

and client…

import it.s4sytems.java.*;
import java.io.*;
import java.net.*;

public class Client
{
    public static void main(String arg[]) throws IOException, ClassNotFoundException
    {
        Socket s = new Socket("localhost", 18000);

        String matricola = "616002424";

        File directory = new File(System.getProperty("user.dir") + "\\" + matricola);
        directory.mkdir();

        File file = File.createTempFile("7897_", null, directory);

        String originalName = new FileOverObjectStream(file).receiveFile(s);

        System.out.println(originalName);

        s.close();


        File file2 = new File(directory, originalName);
        System.out.println( file.renameTo( file2 ) );
        System.out.println( file.getAbsoluteFile());
        System.out.println( file2.getAbsoluteFile());
    }
}

Probably it’s a stupid thing, but I can’t see it, so I need your help, please.

Thank you

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T17:47:08+00:00Added an answer on May 23, 2026 at 5:47 pm

    Your ObjectInput/OutputStream code is flawed in all the ways Alex noted. I wouldn’t use it at all, I would just use raw I/O. The canonical way to copy a stream in Java is as follows:

    int count;
    byte[] buffer = new byte[8192]; // or more, but megabytes is pointless as the network will packetize anyway
    while ((count = in.read(buffer)) > 0)
    {
      out.write(buffer, 0, count);
    }
    

    Use that same code when both sending and receiving the file. If you want to send > 1 file per connection, you need to prefix all that by sending the file name and length, which you can do with DataOutputStream.writeUTF()/writeLong(), and DataInputStream.readUTF()/readLong() at the receiver, and modify the loop control to read exactly that many bytes:

    long remaining = size; // the file size read from the network
    while ((count = in.read(buffer, 0, remaining > buffer.length ? buffer.length : (int)remaining)) > 0)
    {
        out.write(buffer, 0, count);
        remaining -= count;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Good afternoon, This should be an easy one. I've done the cookie-cutter default ASP.NET
This afternoon, upon noticing a broken build and the fact that some files looked
I took the plunge this afternoon and began studying LINQ, so far just mucking
I had some time this afternoon to run a head to head comparison between
I ran across this situation this afternoon, so I thought I'd ask what you
I was testing on a customer's box this afternoon which has Windows Vista (He
Good morning, afternoon, evening or night (depending on your timezone). This is just a
This afternoon I walked my iPhone 4 into the Apple Store to see if
I started a new project this afternoon and now that I've decided to write
This afternoon has been a crash course for me in terms of handles, Safe

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.