文件io性能问题,欢迎大家讨论一下
在写一个上传下载程序的时候遇到以下的问题:
程序由客户端和服务器端构成,程序本身运行没有问题,文件也能正常传输
但实际在本机上运行发现:
程序传输10M以内的程序很快,不到40秒就可以完成。
但如果数据大于10M,前面的数据传输很快,10M以后的数据传输很慢,数据约大就越慢。
我测试的数据是50M,竟然要传送将近10分钟(这还是服务器和客户端都在本机上运行)如果用到互联网上,传输速度肯定会更慢了。
不知道大家是怎样解决这种问题的?
客户端从文件中读取数据,再通过socket发送到服务器上
FileInputStream infile = new FileInputStream(file);
OutputStream outtoFile=socketfile.getOutputStream();
byte[] b=new byte[255];
int bytesread=255;
while((bytesread=infile.read(b,0,bytesread))!=-1)
{
outtoFile.write(b,0,bytesread);
}
outtoFile.flush();
服务器端从socket中读取数据,然后存到文件中:
System.out.println("服务器端口为:"+server.getLocalPort());
Socket s=server.accept();
s.setSoTimeout(2000);
InputStream infile=s.getInputStream();
FileOutputStream outtoFile;
outtoFile=new FileOutputStream(outFile);
byte[] b=new byte[1023];
int bytesread=1023;
while((bytesread=infile.read(b,0,bytesread))!=-1)
{
//System.out.print(bytesread+" ");
outtoFile.write(b,0,bytesread);
}