我的應用程序無法通過套接字連接正確傳輸數據並將其正確寫入文件。超過65,535字節的文件被損壞,不再被設計運行它們的程序識別。如何正確寫入文件數據?
我已經能夠成功發送小的.doc和.txt文件,但.mp3 .wmv .m4a .avi和其他任何內容都無法正常工作。大文檔也沒有。
我已經找遍了互聯網尋找解決這個問題的方法。我已經反覆調整了I/O代碼來解決這個問題,但它仍然不起作用!這是處理髮送和接收文件的超類中的I/O代碼。如果您需要更多信息/其他代碼部分,請告訴我。
protected void sendFile() throws IOException {
byte[] bytes = new byte[(int) file.length()];
buffin = new BufferedInputStream(new FileInputStream(file));
int bytesRead = buffin.read(bytes,0,bytes.length);
System.out.println(bytesRead);
out = sock.getOutputStream();
out.write(bytes,0,fileBytes);
out.flush();
out.close();
}
protected void receiveFile() throws IOException {
byte[] bytes = new byte[fileBytes];
in = sock.getInputStream();
for(int i=0;i<fileBytes;i++) {
in.read(bytes);
}
fos = new FileOutputStream("/Datawire/"+fileName);
buffout = new BufferedOutputStream(fos);
buffout.write(bytes,0,fileBytes);
buffout.flush();
buffout.close();
}
更新的代碼(即工作):
protected void sendFile() throws IOException {
if((file.length())<63000) {
byte[] bytes = new byte[(int)file.length()];
buffin = new BufferedInputStream(new FileInputStream(file));
buffin.read(bytes,0,bytes.length);
out = sock.getOutputStream();
out.write(bytes,0,bytes.length);
out.close();
} else {
byte[] bytes = new byte[32000];
buffin = new BufferedInputStream(new FileInputStream(file));
out = sock.getOutputStream();
int bytesRead;
while((bytesRead = buffin.read(bytes))>0) {
out.write(bytes,0,bytesRead);
}
out.close();
}
}
protected void receiveFile() throws IOException {
if(fileBytes<63000) {
byte[] bytes = new byte[32000];
in = sock.getInputStream();
System.out.println(in.available());
in.read(bytes,0,fileBytes);
fos = new FileOutputStream("/Datawire/"+fileName);
buffout = new BufferedOutputStream(fos);
buffout.write(bytes,0,bytes.length);
buffout.close();
} else {
byte[] bytes = new byte[16000];
in = sock.getInputStream();
fos = new FileOutputStream("/Datawire/"+fileName);
buffout = new BufferedOutputStream(fos);
int bytesRead;
while((bytesRead = in.read(bytes))>0) {
buffout.write(bytes,0,bytesRead);
}
buffout.close();
}
}
接收器如何知道要讀取多少字節?似乎你錯過了那個。您假定大小,直到滿足大小,然後將文件寫入磁盤。 –
@Rob_Goodwin請注意發送文件之前運行的發送和接收信息方法。諸如文件名和文件大小的信息被髮送到那裏的接收端。文件大小由接收器的變量fileBytes表示。 – bgroenks