WonderfulWonder
WonderfulWonder

Reputation: 555

Java: Transferring File over TCP

I'm in the midst of trying to send a file, and in particular large files, from server to client. I can send small files but atm large files do not work.

Server

Socket socket = serverSocket.accept();
byte[] data = new byte[(int)myFile.length()];

FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(data, 0, data.length);

OutputStream oStream = socket.getOutputStream();
oStream.write(data, 0, data.length);

Client

byte[] data = new byte[4096];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("output.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);

int bytesRead = is.read(data, 0, data.length);
int counter = bytesRead;

// while (-1 != (bytesRead = is.read(data, 0, data.length))) 
// {
//     bos.write(data, 0, bytesRead);
// }

bos.write(data, 0, bytesRead);

With this code i'm able to transfer a simple text file successfully. With the commented out section uncommented (and excluding the last line) i thought i'd still be able to send a simple text file and in addition large files like a 200mb video. Obviously, it failed and here i am. Hope someone could give me a hand.

EDIT: Error with while loop (and no last line) is that nothing is written in the txt file

Upvotes: 2

Views: 366

Answers (1)

user207421
user207421

Reputation: 311039

Get rid of the first read and the last write and just use the code that is commented out. That's the only code that actually works.

Upvotes: 1

Related Questions