W
windofsun
Unregistered / Unconfirmed
GUEST, unregistred user!
hyzou:
现在又有了问题:从客户端上传时,直接用长度等于文件长度的byte数组缓冲。服务器端接收时,则用1024字节来缓冲,我以为这样可以加快速度。但实际情况是:服务器保存后的文件比客户端上传的文件稍大了点。如果只能一个byte一个byte去读,将来目标客户端B来取数据的时候那不是慢的要死了?
我该如何是好呢:(
// 从客户端上传
// 以流的形式,从文件到Socket
private boolean fileToSocket(String pFileName, Socket pSocket) throws IOException
{
File fileUpload = new File(pFileName);
FileInputStream finUpload = new FileInputStream(fileUpload);
try
{
// 文件长度
int intLength = (int)fileUpload.length();
// 保存到缓冲数组
byte[] buf = new byte[intLength];
OutputStream soutUpload;
soutUpload = pSocket.getOutputStream();
if (finUpload.read(buf) <= 0)
{
System.err.println("读取文件错误!");
return false;
}
soutUpload.flush();
try
{
soutUpload.write(buf);
}
catch (IOException e)
{
return false;
}
}
finally
{
finUpload.close();
}
return true;
}
// 服务器端,从端口接收数据
private void sockToFile(String pFileName, Socket pSocket) throws IOException
{
FileOutputStream foutReceive = new FileOutputStream(pFileName);
try
{
// 每次读取1024字节
byte[] buf = new byte[1024];
InputStream sinReceive;
sinReceive = pSocket.getInputStream();
StringBuffer strBuf = new StringBuffer(1024);
int intReceive;
while (true)
{
intReceive = sinReceive.read(buf, 0, buf.length);
if (intReceive == -1)
break;
strBuf.append(new String(buf, "ISO-8859-1"));
}
System.out.println("length ="+strBuf.toString().length());
System.out.println("length ="+strBuf.toString().trim().length());
foutReceive.write(strBuf.toString().trim().getBytes("ISO-8859-1"));
}
finally
{
foutReceive.close();
}
}
现在又有了问题:从客户端上传时,直接用长度等于文件长度的byte数组缓冲。服务器端接收时,则用1024字节来缓冲,我以为这样可以加快速度。但实际情况是:服务器保存后的文件比客户端上传的文件稍大了点。如果只能一个byte一个byte去读,将来目标客户端B来取数据的时候那不是慢的要死了?
我该如何是好呢:(
// 从客户端上传
// 以流的形式,从文件到Socket
private boolean fileToSocket(String pFileName, Socket pSocket) throws IOException
{
File fileUpload = new File(pFileName);
FileInputStream finUpload = new FileInputStream(fileUpload);
try
{
// 文件长度
int intLength = (int)fileUpload.length();
// 保存到缓冲数组
byte[] buf = new byte[intLength];
OutputStream soutUpload;
soutUpload = pSocket.getOutputStream();
if (finUpload.read(buf) <= 0)
{
System.err.println("读取文件错误!");
return false;
}
soutUpload.flush();
try
{
soutUpload.write(buf);
}
catch (IOException e)
{
return false;
}
}
finally
{
finUpload.close();
}
return true;
}
// 服务器端,从端口接收数据
private void sockToFile(String pFileName, Socket pSocket) throws IOException
{
FileOutputStream foutReceive = new FileOutputStream(pFileName);
try
{
// 每次读取1024字节
byte[] buf = new byte[1024];
InputStream sinReceive;
sinReceive = pSocket.getInputStream();
StringBuffer strBuf = new StringBuffer(1024);
int intReceive;
while (true)
{
intReceive = sinReceive.read(buf, 0, buf.length);
if (intReceive == -1)
break;
strBuf.append(new String(buf, "ISO-8859-1"));
}
System.out.println("length ="+strBuf.toString().length());
System.out.println("length ="+strBuf.toString().trim().length());
foutReceive.write(strBuf.toString().trim().getBytes("ISO-8859-1"));
}
finally
{
foutReceive.close();
}
}