要实现更短的时间,您可以在文件读取期间检查/搜索文本。老实说,这取决于原始文本是否根本没有新行(如果是这种情况,性能将相同)。
但在解决这个问题之前,我相信您从 URL 中读取的方式是错误的!您在第二次调用期间添加字符串时调用了readLine ()方法两次!所以你在每次迭代中都跳过了一行!
它认为应该这样做:
public class ReadData {
public static void main ( String [] args ) throws IOException {
StringBuilder text = new StringBuilder ();
URL url = new URL ( url );
HttpURLConnection conn = (HttpURLConnection) url.openConnection ();
BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn.getInputStream () ) );
String line = null;
while ( ( line = rd.readLine () ) != null ) {
text.append ( line );
text.append ( "\n" );
}
rd.close ();
}
}
现在要搜索您需要的介于startReading和endReading之间的文本值,您可以这样做:
public static void main ( String [] args ) throws IOException {
// Calendar object used to know when the iteration started
Calendar start = Calendar.getInstance ();
SimpleDateFormat displayDate = new SimpleDateFormat ( "HH:mm:ss SSS" );
System.out.println( "Iteration started at : " + displayDate.format ( start.getTime () ) );
String line = null;
boolean startReadingFound = false;
boolean endReadingFound = false;
while ( ( line = rd.readLine () ) != null ) {
text.append ( line );
text.append ( "\n" );
// Check if 'startReading' is previously found
if ( startReadingFound == false ) {
// Search for the 'startReading' string
int startIndex = line.indexOf ( startReading );
if ( startIndex != -1 ) {
// 'startReading' found
startReadingFound = true;
// Search for the 'endReading' string, it may be on the same line
int endIndex = line.indexOf ( endReading );
if ( endIndex == -1 ) {
// 'endReading' not found
value.append ( line.substring ( startIndex + startReading.length () ) );
value.append ( "\n" );
}
else {
// 'endReading' found
endReadingFound = true;
value.append ( line.substring ( startIndex + startReading.length () , endIndex ) );
value.append ( "\n" );
}
}
}
// Check if 'endReading' is previously found
else if ( endReadingFound == false ) {
// Search for the 'endReading' string
int endIndex = line.indexOf ( endReading );
if ( endIndex == -1 ) {
// 'endReading' not found
value.append ( line );
value.append ( "\n" );
}
else {
// 'endReading' found
endReadingFound = true;
value.append ( line.substring ( 0 , endIndex ) );
value.append ( "\n" );
}
}
}
rd.close ();
// Calendar object used to know when the iteration ended
Calendar end = Calendar.getInstance ();
System.out.println( "Iteration ended at : " + displayDate.format ( end.getTime () ) );
System.out.println( "Iteration duration : " + ( end.getTimeInMillis () - start.getTimeInMillis () ) + " milliseconds." );
}
如您所见,首先您可以开始在每一行中查找startReading字符串。如果找到它,则开始添加(在开始阅读字符串之后)行,直到找到endReading字符串。
为了知道在 while 循环中花费的确切时间,我添加了我正在显示的日历对象,因此您可以知道确切的持续时间(以毫秒为单位)。
试试看,如果它解决了你的问题,请告诉我。