0

I'm having troubles with files in Java.

The issue is: I'm trying to copy a file (not only text, any kind) from one side of a socket to another. I read the file with a BufferedReader (byte by byte) and write them on a file with a FileOutputStream.

It works fine, but when I open the file it is not the same as te original, it is writing the bytes on a text file or something like that.

A piece of code:

        in = new BufferedInputStream(s.getInputStream());
        byte b[] = new byte[MAX_LENGTH];
        File f = new File(name);
        FileOutputStream fos = new FileOutputStream(name);
        for(int i = 0; i < segments; i++){
            in.read(b,i*MAX_LENGTH,MAX_LENGTH);
            fos.write(b);
        }

Where s is a opened socket (working fine), name the name of the file and segments the number of segments sent through the socket (segments of MAX_LENGTH).

Cœur
  • 37,241
  • 25
  • 195
  • 267
Victor
  • 23
  • 1
  • 6
  • Look at a similar problem http://stackoverflow.com/questions/9520911/java-sending-and-receiving-file-byte-over-sockets?rq=1 I hope this helps. – amudhan3093 Aug 23 '13 at 18:49
  • Thanks, but didn't help too much :( – Victor Aug 23 '13 at 20:57
  • *I read the file with a BufferedReader (byte by byte)*: this doesn't make sense. A BufferedReader, as all thr Readers, reads chars, not bytes. Readers and Writers are for text. Streams are for bytes. Since you need to read and write bytes, you should not use a Reader. Post your relevant code. – JB Nizet Aug 23 '13 at 21:19
  • Thanks too much JB Nizet, THAT was the problem, I was using the wrong kind to read, now with Streams it works perfectly. – Victor Aug 24 '13 at 09:20

2 Answers2

0

You assume that you can read MAX_LENGTH bytes with each read call. This may not be the case.

read returns the number of bytes actually read from the stream. Just write that many bytes to the output stream in each loop iteration.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

Your copy code is wrong. You are ignoring the result returned by read(). Memorize this loop. It is the canonical way to copy streams in Java.

while ((count = in.read((buffer)) >= 0)
{
   out.write(buffer, 0, count);
}

Compare with your code. Make the buffer any size you like, the larger the better.

user207421
  • 305,947
  • 44
  • 307
  • 483