Skip to Main Content

New to Java

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!

Client server file transfer always got 4380B missing

807600Oct 30 2007 — edited Nov 5 2007
Hi, I send file from server to client using the following method, which can send file successfully
public boolean sendFile(Socket toClient, String filename)
{


try
{
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream in = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream( toClient.getOutputStream() );

int i;
byte bytes[] = new byte[fis.available()];
while ((i= in.read(bytes))!=-1)
{
System.out.println(i==bytes.length);
out.write(bytes);
out.flush();
bytes = new byte[fis.available()];
if (bytes.length<1)
break;
}

in.close();

System.out.println("file "+filename+" has been sent to "+toClient.getInetAddress().getHostAddress());

return true;
}
catch(Exception e)
{
System.out.println(e);
return false;
}
}


and using the following method to recieve file in the client side,


private boolean receiveFile(String filename,long fileLength)
{

boolean recieved = false;
try
{

FileOutputStream fos = new FileOutputStream("c:\\"+filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream( clientManager.getSocket().getInputStream());

int j=0;

if (fileLength > Integer.MAX_VALUE)
{
System.out.println("File is too large!");
}

while(bis.available()==0)
{
Thread.sleep(100);
}

byte[] bytes = new byte[bis.available()];

int offset = 0;
int numRead = 0;
while ((numRead=bis.read(bytes, offset, bytes.length-offset)) >= 0)
{
bos.write(bytes, offset, numRead);
// if (numRead<bytes.length)
// offset = numRead;
// else
// offset = 0;
bytes = new byte[bis.available()];
}


if (offset < bytes.length)
{
throw new IOException("Could not completely read file ");
}


bos.close();

recieved = true;

}
catch(IOException e)
{
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return recieved;


}

Each time the client just recieve the file of 4380B missing. No matter how big the file is, 30KB or 5M.

Any suggestions?

Edited by: Carrie on Oct 30, 2007 3:35 AM

Edited by: Carrie on Oct 30, 2007 3:57 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 3 2007
Added on Oct 30 2007
4 comments
191 views