简体   繁体   中英

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

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 ). As of Java 7 you can do

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

instead of the wile loop.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM