Question

I'm trying to write a mini FTP application that reads binary data from a file and sends it to a client. My program usually does not behave as desired and usually ends up sending the file, but not doing it completely (i.e. send text file and the content is blank). I think it may be because I use the filereader to read the line, although I do not quite understand why this would be a problem. Here is the relevant code:

File file = new File(rootDirectory, name);
int filenum = (int)file.length();
long filelen = file.length();
System.out.println("File is: " + filenum + " bytes long");
socketOut.writeLong(filelen);
fileIn = new BufferedReader(new FileReader(file));
System.out.println("Sending: " + name);

while((line = fileIn.readLine()) != null){
       socketOut.writeBytes(line);
       socketOut.flush();
}
Was it helpful?

Solution

The problem is that Readers/writers read text (as opposed to Input~/OutputStreams). FileReader internally uses the default operating system encoding. That conversion will never do for binary files. Also note, that readLine discards the line ending (\r\n, \n or \u0085). As of Java 7 you can do

Files.copy(file.toPath(), socketOut);

instead of the wile loop.

OTHER TIPS

Joop's solution is perfect for Java7 (or later). If you are stuck on an older version (or want to extend your tool arsenal anyway), have a look at the following free libraries:

  • Apache Commons IO (actually all Apache Commons are interesting to look at). There you can do IOUtils.copy(...)
  • Google Guava There it is a little more complicated but flexible. Use ByteSource.copyTo(ByteSink)

I like the caching in the Google libraries, pretty neat

If you don't have Java 7 and don't want to add external libraries, the canonical copy loop in Java for streams is as follows:

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

where count is an int, and buffer is a byte[] of any non-zero size. It doesn't have to be anywhere near the size of the file. I usually use 8192.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top