android update progress bar while reading records from a text file

自古美人都是妖i 提交于 2019-12-13 04:30:14

问题


I am trying to find the best way to update a Progress Bar while reading in records from a text file stored on internal storage. In my activity fragment I use a button to load a progress dialog with a progress bar to be updated.

The problem is if a the text file has over 2000+ records (1 record per line) should I count the number of lines in the text file prior to loading the records, and use this value to estimate the percentage complete for the Progress Bar? or Is there a more elegant way of doing this?


回答1:


The accuracy for the progress bar isn't critical, and it's more important to be responsive. I'd just grab the file's size and update the progress bar as bytes read/file size. Reading the entire file to figure out its record count could be prohibitively expensive, and it won't gain you much.




回答2:


If you want to know the size (in terms of lines) of the file, and it has no more lines that Long.MAX_VALUE (which is 9223372036854775807), you can use this method:

LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));  
lnr.skip(Long.MAX_VALUE);  
System.out.println(lnr.getLineNumber());

(Extracted from: Number of lines in a file in Java)




回答3:


What about using the file size and counting the number of bytes you read each time?

int sizeInBytes = file.length();
int currentBytes = 0;

//READ A LINE
currentBytes += line.length();
updateProgress((currentBytes/sizeInBytes)*100);


来源:https://stackoverflow.com/questions/18810516/android-update-progress-bar-while-reading-records-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!