我已经编写了一个服务器和一个客户端来实现 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/