java - 某些文件格式通过 FTP 损坏

标签 java sockets file-handling

我已经编写了一个服务器和一个客户端来实现 FTP,如果我创建文本文件并发送它们,它们就可以正常工作。但一旦我发送其他格式的文件,客户端收到的文件就会损坏。这是我发送文件的代码

           try
           {
              fis=new FileInputStream(filenm);
           }

           catch(FileNotFoundException exc)
           {
              filexists=false;
              System.out.println("FileNotFoundException:"+exc.getMessage());
           }
           if(filexists)
           {
               System.out.println("sent");
               sendBytes(fis, output);
               fis.close();
            }

private static void sendBytes(FileInputStream f,OutputStream op)throws Exception
 {
  byte[] buffer=new byte[1024];
  int bytes=0;

  while((bytes=f.read(buffer))!=-1)
  {
   op.write(buffer,0,bytes);
  }
 }

fis - FileInputStream 对象 输出 - OutputStream 对象 (Socket.getOutputStream())

客户端代码是:

File f=new File(dir,"file2");
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dops=new DataOutputStream(fos);
System.out.println("2nd Stage");
while(done)
{
  fc2=br.read();
  if(fc2==-1)
  {
    done=false;
  }
  else
  {
       dops.write(fc2);
  }
}
fos.close();
System.out.println("File Recieved");

我使用的流正确吗?

最佳答案

听起来您正在以 ASCII 模式发送二进制文件。

在通过发送 PORT 设置数据通道之前,在控制 channel 上发送 TYPE I 而不是 TYPE A PASV 命令。

关于java - 某些文件格式通过 FTP 损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7322717/

相关文章:

java - 网格中的 Vaadin 过滤器

Java邮件 : Socket read timeout

c++ - 使用QTcpSocket实现连续快速使用

c - 使用 C 套接字发送 HTTP 响应

python - Python 中 with 语句中的 file.close() 异常处理

c - C 中的文件处理 : Strip spaces at the beginning and end of text file

java - 将新对象添加到列表中; (for循环不能正常工作)

java - 当用户使用 servlet 关闭浏览器时使 session 无效

java - spring mvc 声明所有 beans 单例

java - 弹出 excel 文件而不是在 apache poi 内部保存