【发布时间】:2014-10-17 00:19:48
【问题描述】:
在尝试了我能想到的一切 2 天后,我无法让此代码正常工作。我知道已经提出并回答了这个确切的问题,但我仍然无法让我的工作正常。我正在尝试通过套接字发送多个文件。
我修改了代码以在每次接收之前接收文件大小,但它仍然无法正常工作。我可以让它将所有数据发送到一个文件中,但是当我应用其他帖子中建议的 while 循环时,它要么只发送 1 个文件然后停止,要么什么都不发送。如果可能的话,有人可以纠正这个问题,以便我继续前进。 iv 遇到这个问题已经快一周了,尽管我明白我需要做什么,但我还是无法确保语法正确。
任何帮助将不胜感激。
接收代码:
private void receiveFile() throws IOException{
String fileToReceive = "test" + increment;
int bytesRead;
int current = 0;
DataInputStream inputs = new DataInputStream(connection.getInputStream());
long fileLength = inputs.readLong();
int total = 0;
//receive file
try{
byte [] mybytearray = new byte [(int)fileLength];
is = connection.getInputStream();
fos = new FileOutputStream(fileToReceive);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
while(fileLength > 0 &&(total = is.read(mybytearray, 0, (int)Math.min(mybytearray.length, fileLength))) != -1){
bos.write(mybytearray, 0, total);
fileLength -= total;
}
System.out.println("File " + fileToReceive + " downloaded (" + current + " bytes read)");
}finally{
// if (fos != null) fos.close();
// if (bos != null) bos.close();
// if (connection != null) connection.close();
}
increment += 1;
}
}
发送代码
public void sendFile(String file) throws IOException, ClassNotFoundException{
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream dos = null;
DataOutputStream outputs = new DataOutputStream(connection2.getOutputStream());
try{
dos = connection2.getOutputStream();
File myFile = new File (file);
byte [] mybytearray = new byte [(int)myFile.length()];
outputs.writeLong(myFile.length());
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
dos.write(mybytearray,0,mybytearray.length);
System.out.println("Sent " + file + "(" + mybytearray.length + " bytes)");
dos.flush();
}catch(Exception ex){
ex.printStackTrace();
}
finally{
}
}
【问题讨论】:
-
您没有正确复制重复问题中的代码。在接收代码中的读取循环之前,您仍然有一个额外的
read()。此外,您的发送代码假定read()填充缓冲区。它也应该有一个循环。没有必要在两端使用文件大小的缓冲区。 -
我放弃了。我明白我需要做什么,我只是无法正确获取语法。直到上周才使用套接字进行文件传输,虽然它确实可以工作并发送所有文件,但我只是无法将它们分开。如果只有有人会纠正我的代码,这样我就可以看到我哪里出错了……
-
在循环之前摆脱接收代码中的第一次读取。我已经告诉过你了,我已经给你指出了工作代码。
-
我了解接收代码并已删除重复读取。发送代码的 while 循环不在您指出的工作代码中。我的发送代码与我能找到的任何其他人相同...