Search code examples
javafilechannel

Java FileChannel bigger than its content


I am creating a fileChannel to perform memory mapped writing. This fileChannel has a size of 100 bytes. I only write 80 bytes to it. So when I read from that file later on, it adds 5 "0" to the and. Is there any way to set the size or get the size which is written to the file?

Thanks a lot!!

public FileChannel create(String randomFile){
   // create file output stream
   RandomAccessFile raf;
   FileChannel fc = null;

   try {    
      raf = new RandomAccessFile(randomFile, "rw");
      fc = raf.getChannel();
      System.out.println("fc.size() "+ fc.size());      
   } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
   return fc;
}

Solution

  • Use this instead:

    final Path path = Paths.get("thefile");
    final FileChannel fc = FileChannel.open(path, StandardOpenOption.WRITE,
        StandardOpenOption.READ);
    
    // then later:
    
    fc.truncate(80L);
    

    And of course, don't forget to .close(). And ideally you should open your channel using a try-with-resources statement.