0

I have this code for reading data and works fine but I want to change the start point that the data is read from - My DataFile.txt is "abcdefghi" and the output is

1)97                
2)98                                                                       
3)99                                                                            
4)100

I want to start at the second byte so the output would be

1)98              
2)99           
3)100  
4)etc

Code:

import java.io.*;
public class ReadFileDemo3 {
    public static void main(String[] args)throws IOException  {     
        MASTER MASTER = new MASTER();
        MASTER.PART1();
    }
}

class MASTER {
    void PART1() throws IOException{
        System.out.println("OK START THIS PROGRAM");
        File file = new File("D://DataFile.txt");
        BufferedInputStream HH = null;
        int B = 0;
        HH = new BufferedInputStream(new FileInputStream(file));
        for (int i=0; i<4; i++) {
            B = B + 1;   
            System.out.println(B+")"+HH.read());
        }
    }    
}
Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30

1 Answers1

0

You can simple ignore the first n bytes as follows.

HH = new BufferedInputStream(new FileInputStream(file));
int B = 0;
int n = 1; // number of bytes to ignore

while(HH.available()>0) {
    // read the byte and convert the integer to character
    char c = (char)HH.read();
    if(B<n){
        continue;
    }
    B++;
    System.out.println(B + ")" + (int)c);
}

Edit: If you want to access a random location in file, then you need to use RandomAccessFile. See this for detailed examples.

Related SO post:

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • Thank you for your reply but something is not right n doesn't seem to be used :) – Mharles Canson Jun 29 '17 at 20:06
  • what is that something which is not working? I assumed your code is correct and so modified it little bit as you mentioned - you just want to skip the first byte. note that, i didn't run the code to check if its working! – Wasi Ahmad Jun 29 '17 at 21:24
  • Thanks again for your reply I want to go to an exact address/offset ? – Mharles Canson Jun 30 '17 at 01:14
  • Thank you again Sir ill investigate :) – Mharles Canson Jun 30 '17 at 01:33
  • I cant get this working import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class ReadTest { public static void main(String[] args)throws IOException { byte[] magic = new byte[4]; File file = new File("D://test.map"); raf = new RandomAccessFile(file ); raf.seek(0L); raf.readFully(magic); System.out.println(new String(magic)); } } – Mharles Canson Jun 30 '17 at 11:14