• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to read a particular position of a file in java and go back to start and read another position?  RSS feed

 
Sree Lekshmi
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to read a a particular position of a file in java and go back to start and read another position..and create a text file
I am using Buffered Reader here, Below is my code. I am reading everything in a hashmap. When second time Im reading the buffered reader, iam getting record value as null. I tried to set mark and reset. But still it is not working. Any better approach please ?

private HashMap extractControlRecord(long len, BufferedReader br) throws IOException {
HashMap<Integer, String> extractMap = new HashMap<Integer, String>();
// Position 90
long skipped = br.skip(len-80);
String record = br.readLine();
// locate the position marker
int pos = record.indexOf("99");

if (pos != -1) {

log.debug("position = " + pos);
// locate the item count
extractMap.put(0, record.substring(pos + 16, pos + 24));

log.debug("itemcount = " + extractMap.get(0));
// locate the file total amount
extractMap.put(1, record.substring(pos + 24, pos + 40));
log.debug("fileamount = " + extractMap.get(1));

}

long skipped2 = br.skip(len-160);
String record2 = br.readLine();
// locate the position marker
int pos2 = record.indexOf("90");
log.info("position is ----->: " + pos2);
if (pos2 != -1) {

log.debug("position = " + pos2);
// locate the item count
extractMap.put(2, record.substring(pos2 + 10, pos2 + 30));

// locate the file total amount
extractMap.put(3, record.substring(pos2 + 24, pos2 + 40));

}

return extractMap;

}
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to read a a particular position of a file in java

The seek() method in the RandomFileAccess class will do that.

Please edit your post and wrap the code in code tags to preserve formatting and add highlights to make the code readable.

Does the stream support the mark() operation?  Use markSupported() to test.
 
Sree Lekshmi
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I printed markSupport and it says "true"..But still not working..I marked the beginning of file and resetted, but the record always read 0 second time.

First time it is printing..Second time i set the mark as length of the file and reset to that position and skipped one character, while printing br.readLine...it is giving null

 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you post a small, simple program that compiles, executes and shows the problem?  Be sure to wrap the code in code tags.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!