一次读取一行文本,并将该行单独添加到字符串上,这在提取每一行和如此多的方法调用的开销方面都非常耗时。
我可以通过分配一个大小合适的字节数组来保存流数据来获得更好的性能,并在需要时用较大的数组迭代替换它,并尝试读取尽可能多的数组。
由于某种原因,当代码使用HTTPUrlConnection返回的InputStream时,Android多次无法下载整个文件,因此我不得不求助于BufferedReader和手动滚动超时机制,以确保获取或取消整个文件转移。
private static final int kBufferExpansionSize = 32 * 1024;
private static final int kBufferInitialSize = kBufferExpansionSize;
private static final int kMillisecondsFactor = 1000;
private static final int kNetworkActionPeriod = 12 * kMillisecondsFactor;
private String loadContentsOfReader(Reader aReader)
{
BufferedReader br = null;
char[] array = new char[kBufferInitialSize];
int bytesRead;
int totalLength = 0;
String resourceContent = "";
long stopTime;
long nowTime;
try
{
br = new BufferedReader(aReader);
nowTime = System.nanoTime();
stopTime = nowTime + ((long)kNetworkActionPeriod * kMillisecondsFactor * kMillisecondsFactor);
while(((bytesRead = br.read(array, totalLength, array.length - totalLength)) != -1)
&& (nowTime < stopTime))
{
totalLength += bytesRead;
if(totalLength == array.length)
array = Arrays.copyOf(array, array.length + kBufferExpansionSize);
nowTime = System.nanoTime();
}
if(bytesRead == -1)
resourceContent = new String(array, 0, totalLength);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
if(br != null)
br.close();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
编辑:事实证明,如果您不需要重新编码内容(即,您希望内容按原样),则不应使用任何Reader子类。只需使用适当的Stream子类。
将以下方法的相应行替换为前面方法的开头,以使其速度额外提高2到3倍。
String loadContentsFromStream(Stream aStream)
{
BufferedInputStream br = null;
byte[] array;
int bytesRead;
int totalLength = 0;
String resourceContent;
long stopTime;
long nowTime;
resourceContent = "";
try
{
br = new BufferedInputStream(aStream);
array = new byte[kBufferInitialSize];