1

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;
}
WeSt
  • 2,628
  • 5
  • 22
  • 37

2 Answers2

2

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.

fge
  • 119,121
  • 33
  • 254
  • 329
  • I get this error, when doing this: The method open(Path, OpenOption...) in the type FileChannel is not applicable for the arguments (Path, FileChannel.MapMode) – Christina Kraus Jan 02 '15 at 18:13
  • Ah, well, a quick look at the javadoc should have told you what's wrong, and even the error in fact. Replace `FileChannel.MapMode.WRITE` with `StandardOpenOption.WRITE`. – fge Jan 02 '15 at 18:36
  • I'm sorry, you are right. Now I get the problem that I cannot map the file to memory: `MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, position, bufferSize);`This throws a nonReadableChannel Exception, I don't know why... – Christina Kraus Jan 02 '15 at 23:42
  • Well, you did specify that you wanted to open it for write but not read; add `StandardOpenOption.READ` as an open option, that should do it – fge Jan 03 '15 at 00:01
  • The truncate does the job I needed, it reduces the size to the written amount. I wasn't aware of this method. How the file is opened actually doesn't matter. – Christina Kraus Jan 04 '15 at 09:58
  • Hi, I also had the same problem and `truncate()` helped. But do you have a reason why `FileChannel` allocates a bigger file than needed? – elect Sep 22 '17 at 16:07
0

I think setLength() is what you're looking for. Java doc.

markspace
  • 10,621
  • 3
  • 25
  • 39