Java 通过套接字进行文件传输-空文件
我在将文件从服务器传输到客户端时遇到问题。传输完成后,将创建文件,但其为空。请注意,当我将它从客户端发送到服务器时,它可以工作。有时,在long fileLength=dis.readLong和String fileName=dis.readUTF时也会出现EOF异常 客户:Java 通过套接字进行文件传输-空文件,java,sockets,file-transfer,Java,Sockets,File Transfer,我在将文件从服务器传输到客户端时遇到问题。传输完成后,将创建文件,但其为空。请注意,当我将它从客户端发送到服务器时,它可以工作。有时,在long fileLength=dis.readLong和String fileName=dis.readUTF时也会出现EOF异常 客户: private void sendFile(String path) throws IOException { BufferedOutputStream bos = new BufferedOutputStream
private void sendFile(String path) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File file = new File(path);
long length = file.length();
dos.writeLong(length);
String name = file.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1)
bos.write(theByte);
dos.close();
bis.close();
displayMessage(MESSAGE_SENT);
}
private void getFile() throws IOException {
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
long fileLength = dis.readLong();
String fileName = dis.readUTF();
File file = new File(System.getProperty("user.dir") + "/" + fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int theByte = 0;
while((theByte = bis.read()) != -1)
bos.write(theByte);
bos.close();
dis.close();
displayMessage(MESSAGE_DOWNLOADED);
}
服务器:
private void sendFile(String path) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File file = new File(path);
long length = file.length();
dos.writeLong(length);
String name = file.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1)
bos.write(theByte);
dos.close();
bis.close();
displayMessage(MESSAGE_SENT);
}
private void getFile() throws IOException {
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
long fileLength = dis.readLong();
String fileName = dis.readUTF();
File file = new File(System.getProperty("user.dir") + "/" + fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++)
bos.write(bis.read());
bos.close();
dis.close();
displayMessage(MESSAGE_DOWNLOADED);
}
我认为问题在于不刷新输出流。像这样:
int theByte = 0;
while((theByte = bis.read()) != -1)
bos.write(theByte);
dos.flush();
dos.close();
bis.close();
不做。接近呼叫刷新?我的错。DataOutputStream是FilterOutputStream的一个子类,API也说关闭刷新。很抱歉。但是,您确实在客户端sendFile方法中显式地刷新它;p和我没有在那里调用dos.close-无论如何,我测试了它,但它不起作用:当你通过调试器进入你的客户机代码时,你能确认数据到达了并且写文件本身没有问题吗?