一次只读取一行文本,并逐个将该行附加到字符串中,这样做在提取每一行和执行如此多的方法调用时都非常耗时。
通过分配一个足够大的字节数组来保存流数据并进行迭代替换,尝试尽可能多地读取数组可以容纳的内容,我能够获得更好的性能。
由于某种原因,当代码使用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)
{
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];