title: Search for a string in large file and save it's position in Java
body: <p>I'm searching for a way to parse large files (about 5-10Go) and search for position (in byte) of some recurrent strings, the fastest as possible.</p>
  
  <p>I've tried to use the RandomAccessFile reader by doing something like bellow:</p>
  
  <pre><code>RandomAccessFile lecteurFichier = new RandomAccessFile(&lt;MyFile&gt;, "r");
  while (currentPointeurPosition &lt; lecteurFichier.length()) {
       char currentFileChar = (char) lecteurFichier.readByte();
       // Test each char for matching my string (by appending chars until I found my string)
       // and keep a trace of all found string's position
  }
  </code></pre>
  
  <p>The problem is this code is too slow (maybe because I read byte by byte ?).</p>
  
  <p>I also tried the solution bellow, which is perfect in term of speedness but I can't get my string's positions.</p>
  
  <pre><code>    FileInputStream is = new FileInputStream(fichier.getFile());
  
      FileChannel f = is.getChannel();
  
      ByteBuffer buf = ByteBuffer.allocateDirect(64 * 1024);
  
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();
  
      long len = 0;
      while ((len = f.read(buf)) != -1) {
          buf.flip();
  
          String data = "";
          try {
              int old_position = buf.position();
              data = decoder.decode(buf).toString();
              // reset buffer's position to its original so it is not altered:
              buf.position(old_position);
          }
          catch (Exception e) {
              e.printStackTrace();
          }
  
          buf.clear();
      }
  
      f.close();
  </code></pre>
  
  <p>Does anyone has a better solution to propose ?</p>
  
  <p>Thank you in advance (and sorry for my spelling, I'm french)</p>