0

Why opening a FileChannel in the following way:

FileChannel.open(path,StandardOpenOption.READ,StandardOpenOption.APPEND);

gives an exception?

I know that it's specified by the API. However I would like to know why it's allowed with the combination of READ, WRITE and it is not with READ and APPEND.

Thanks in advance.

Rollerball
  • 12,618
  • 23
  • 92
  • 161

1 Answers1

-1

Because it doesn't mean anything. You can't append to a file while only reading from it.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • what if you want to write append and then read what from it by using the same file? It forces to use 2 FileChannel one toRead and one to Write... – Rollerball Aug 11 '13 at 12:09
  • No it doesn't. Nobody is stopping you from specifying StandardOpenOption.WRITE in addition to READ and APPEND. Your question doesn't make sense. – user207421 Aug 11 '13 at 23:09
  • 1
    "Your question doesn't make sense." To me your comment does not make sense as following your instructions leads to the same exception. `Exception in thread "main" java.lang.IllegalArgumentException: READ + APPEND not allowed`. Thanks for your time though. – Rollerball Aug 12 '13 at 07:03
  • @RollerBall So in other words you *do* want to write to the file? It isn't mentioned in your question. – user207421 Aug 12 '13 at 07:46
  • The only thing I would like to know is, quoting my question:"I would like to know why it's allowed with the combination of READ, WRITE and it is not with READ and APPEND" (or I could add with READ, WRITE and APPEND if you prefer however APPEND implies writing, you can open a file with CREATE and APPEND without specifying WRITE, and still be able to write to the file). – Rollerball Aug 12 '13 at 08:16
  • Wanted just to know if there were any particular reason for it. I can work around. I am just studying for the OCPJP7 and trying to figuring out any possible tricky question. – Rollerball Aug 12 '13 at 08:17
  • However I think that it might be due to the fact that if READ and APPEND would be together.. there might be inconsistencies between what gets read and what gets written if not "synchronized" properly. Waiting for other opinion about it. – Rollerball Aug 12 '13 at 08:22
  • Specifying READ and APPEND does not constitute 'following an instruction' to specify READ, WRITE, and APPEND. – user207421 Nov 29 '15 at 05:58
  • To be clear, specifying `READ+APPEND` or `READ+APPEND+WRITE` results in the same behavior - an `IllegalArgumentException` with message "READ + APPEND not allowed". Note that specifying WRITE is not necessary for `FileChannel.open` if APPEND has already been specified, as stated in the documentation: ["If this option is present then the file is opened for writing..."](http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#open(java.nio.file.Path,%20java.util.Set,%20java.nio.file.attribute.FileAttribute...)). – hendalst Nov 29 '15 at 09:01