我试图在客户端 - 服务器之间传输文件,如果文件大于12MB而不是通过块发送,否则它会正常发送。我的主要问题是,每次我传输的东西都比原来的更多,我需要在完成后使用摘要消息,因此它不会按原样运行,另一个是当我尝试发送文件时通过网络,客户端读取文件的发送速度比服务器写入的速度快,因此客户端关闭程序关闭连接,破坏文件。我的转帐代码如下:
这是客户端转移代码:
if(fSize>maxfileSize){
totbLidos = 0;
byte[] fBytes = new byte[fBsize];
while(totbLidos < fSize){
int bRemain = (int) f.length() - totbLidos;
if(bRemain < fBsize){
fBsize = bRemain;
}
int bRead = tFile.read(fBytes, 0, fBsize);
tServidor.write(fBytes, 0, fBsize);
tServidor.flush();
if(bRead>0){
totbLidos+=bRead;
}
System.out.println("Total Bytes Lidos: " + totbLidos);
}
tFile.close();
System.out.println("Ficheiro enviado");
cliente.close();
}
else{
totbLidos = 0;
byte[] fBytes = new byte[fSize];
while(totbLidos < fSize){
int bRead = tFile.read(fBytes,0,fSize);
if(bRead>0){
totbLidos+=bRead;
}
tServidor.write(fBytes, 0, fSize);
System.out.println("Total Bytes Lidos: " + totbLidos);
tServidor.flush();
}
tFile.close();
System.out.println("Ficheiro enviado");
cliente.close();
}
}
服务器转移代码:
if(fSize > maxfileSize){
totbLidos = 0;
DataInputStream tFile = new DataInputStream(cliente.getInputStream());
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(fName));
byte[] fBytes = new byte[fBsize];
while(totbLidos < fSize){
int bRemain = size - totbLidos;
if(bRemain < fBsize){
fBsize = bRemain;
}
int bRead = tFile.read(fBytes, 0, fBsize);
fos.write(fBytes);
fos.flush();
if(bRead>0){
totbLidos+=bRead;
}
System.out.println("Bytes lidos: " + bRead);
System.out.println("Total Bytes Escritos: " + totbLidos);
}
System.out.println("Ficheiro recebido");
fos.close();
tFile.close();
cliente.close();
servidor.close();
}
else if(fSize < maxfileSize){
totbLidos = 0;
DataInputStream tFile = new DataInputStream(cliente.getInputStream());
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(fName));
byte[] fBytes = new byte[fSize];
while(totbLidos < fSize){
int bRead = tFile.read(fBytes,0,fSize);
fos.write(fBytes);
fos.flush();
if(bRead>0){
totbLidos+=bRead;
}
System.out.println("Total Bytes Escritos: " + totbLidos);
}
System.out.println("Ficheiro recebido");
fos.close();
tFile.close();
cliente.close();
servidor.close();
}
}
答案 0 :(得分:2)
您没有写下您在此处阅读的相同字节数。
fos.write(fBytes);
尝试使用
fos.write(fBytes, 0, bRead);
答案 1 :(得分:0)
除了@Peter Lawrey的回答,我建议您重用Apache Commons IO API以避免将来出现这种错误:
IOUtils.copyLarge(InputStream input, OutputStream output, long inputOffset, long length)