title: Manipulate big Textfiles in Java
body: <p>I was wondering how do you manipulate big Textfiles in Java, if we assume that the Filesize is larger than the memory. I googled that topic and it shows that most people recommend <code>java.nio</code>for such a task.</p>
  
  <p>Unfortunately I haven't found any documentation on how to manipulate the File. For example read every Line, modify it, write it. I tried something like this, but this doesn't work:</p>
  
  <pre><code>    FileChannel fileChannel = null;
      try {
          fileChannel = new RandomAccessFile(file, "rw").getChannel();
          ByteBuffer buffer = ByteBuffer.allocate(256);
  
          while (fileChannel.read(buffer) != -1) {
              buffer.rewind();
              buffer.flip();
              String nextLine = buffer.asCharBuffer().toString();
              if (replaceBackSlashes) {
                  nextLine = nextLine.replace("\\\\", "/");
              }
              if (!(removeEmptyLines &amp;&amp; StringUtils.isEmpty(nextLine))) {
                  buffer.flip();
                  buffer.asCharBuffer().put(nextLine);
              }
  
              buffer.clear();
          }
      } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } finally {
          if (fileChannel != null) {
              try {
                  fileChannel.close();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      }
  </code></pre>
  
  <p>So what are your recommendations? Also the String <code>nextline</code>, doesn't match anything in my File. Maybe I need to set the encoding?</p>