我在将文件从服务器传输到客户端时遇到问题。传输完成后,文件被创建但是为空。请注意,当我从客户端发送到服务器时,它可以工作。有时我也会在long fileLength = dis.readLong()和String fileName = dis.readUTF()时获得EOF异常。
客户端:
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);
}
答案 0 :(得分:0)
我认为问题在于不刷新输出流。像这样:
int theByte = 0;
while((theByte = bis.read()) != -1)
bos.write(theByte);
dos.flush();
dos.close();
bis.close();