通过套接字连接发送时,Pdf文件无法正确显示文本

时间:2019-02-21 08:03:54

标签: java android

我正在从Java服务器向Android客户端发送pdf文件。但是,当我在手机上查看pdf文件时,文本有时是错误的(只是一些随机符号)。有人知道是什么引起了这个问题吗?

这是服务器的代码:

private void sendPdfToPhone(File pdf) {
    try {
        InputStream iS = new FileInputStream(pdf);
        DataOutputStream dOS = new DataOutputStream(new BufferedOutputStream(this.clientSocket.getOutputStream()));

        String filename = pdf.getName();
        byte[] bytes = new byte[(int) pdf.length()];

        dOS.writeUTF(filename);
        dOS.writeLong(bytes.length);

        byte[] buffer = new byte[8192];
        int bytesRead;
        int bytesSent = 0;
        while ((bytesRead = iS.read(buffer)) > 0) {
            dOS.write(buffer, 0, bytesRead);
            bytesSent += bytesRead;
        }
        dOS.close();
        logger.debug("Sent file " + filename + " to Client: " + bytesSent + " / " + bytes.length);

    } catch (IOException ex) {
        logger.fatal(ex);
    }

}

这是Android客户端的代码:

int bytesRead;
String filename = dIS.readUTF();
long fileSize = dIS.readLong();
byte[] buffer = new byte[1024];

File pdf = new File(context.getCacheDir() + "/" + filename);
if (!pdf.exists()) {
  pdf.createNewFile();
  FileOutputStream fOS = new FileOutputStream(pdf);

  while (fileSize > 0 && (bytesRead = dIS.read(buffer, 0, (int) 
   Math.min(buffer.length, fileSize))) != -1) {
   fOS.write(buffer, 0, bytesRead);
   fileSize -= bytesRead;
 }

 dIS.close();
 dOut.close();
}
pdfFile = pdf;
socket.close();
return pdf;

0 个答案:

没有答案