Search code examples
javafiledataoutputstream

Java reading from file and sending using DataOutputStream


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();
}

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.