• Post Reply Bookmark Topic Watch Topic
  • New Topic

Progress when parsing file?  RSS feed

 
Vladimir Baranovich
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I'm writing a program that needs to parse large text files and place the contents into a StringBuffer(so the contents can be manipulated). I would like to provide a progress bar for users, so they can know the status of the parsing. In order to make the progress bar work, I need to keep track of the "percentage done". I have used the myFile.length() method to get the filesize in bytes but I have yet to discover a way to keep track of how many bytes have been read so far. Is there a simpler way to do this? Much thanks in advance.

-VB
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the JavaRanch, Vladimir.
Except for RandomAccessFile.getFilePointer(), There's no built-in functionality to get how many bytes have been read. You could either keep a running tally of what you've read so far or use StringBuffer.length()
NOTE: text file encoding may make the number of characters in a file not equal the number of bytes
 
Vladimir Baranovich
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your post, I figured out a way to do it although its far from elegant. I read each line of the file into a string and the call myString.getBytes() to decode the string into a byte array. Then I can just keep a running tally of the byte array size. Also I had to add one to the value for each line because the newline character isn't part of the string but it is a part of the filesize (took me a good 20 mins to figure out what was going on with that one). Well, about all I can say is that it works.
 
Neeraj Dheer
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why dont you try the InputStream.available() method?

That method returns the number of bytes still remaining to be read, so a (length() - available()) should give you number of bytes read??
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Neeraj Dheer:
That method returns the number of bytes still remaining to be read


No it doesn't:

public int available() throws IOException

Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream.

Java API Documentation - java.io.InputStream
It can return anything between 0 and the remaining bytes in a file.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!