4

First of all I have a couple hours experience with Java so, If its a bit simple question, sorry about that.

Now, I want to read a file but I dont want to start at the beginning of file instead I want to skip first 1024 bytes and than start reading. Is there a way to do that ? I realized that RandomAccessFile might be useful but I'm not sure.

try {
     FileInputStream inputStream=new FileInputStream(fName);
       // skip 1024 bytes somehow and start reading .
} catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
}
Jonik
  • 80,077
  • 70
  • 264
  • 372
TheGost
  • 147
  • 1
  • 3
  • 8
  • 1
    You could just read 1024 bytes and then do your thing. – Sotirios Delimanolis Jan 04 '14 at 21:36
  • @SotiriosDelimanolis yeap its a way to handle, but isnt it a kind of useless ? – TheGost Jan 04 '14 at 21:39
  • @SotiriosDelimanolis btw after 1024 bytes, sometimes I need to skip part of file so it would be better if I learn to do that – TheGost Jan 04 '14 at 21:40
  • Related: if it's a binary file: http://stackoverflow.com/questions/3624352/jump-on-specific-location-in-binary-file; if it's a text file: http://stackoverflow.com/questions/10102703/read-text-file-from-position-in-java – Jonik Jan 04 '14 at 21:42

2 Answers2

5

You will want to use the FileInputStream.skip method to seek to the point you want and then begin reading from that point. There is more information in the javadocs about FileInputStream that you might find interesting.

dcolish
  • 22,727
  • 1
  • 24
  • 25
  • @dcolish by the way my file is binary .It causes any problem ? – TheGost Jan 04 '14 at 21:53
  • @TheGost: not at all: "[FileInputStream](http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html) is meant for reading streams of raw bytes such as image data." – Jonik Jan 04 '14 at 22:06
0

You could use a method like skipBytes() here

/**
 * Read count bytes from the InputStream to "/dev/null".
 * Return true if count bytes read, false otherwise.
 * 
 * @param is
 *          The InputStream to read.
 * @param count
 *          The count of bytes to drop.
 */
private static boolean skipBytes(
    java.io.InputStream is, int count) {
  byte[] buff = new byte[count];
  /*
   * offset could be used in "is.read" as the second arg
   */
  try {
    int r = is.read(buff, 0, count);
    return r == count;
  } catch (IOException e) {
    e.printStackTrace();
  }
  return false;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249