javaambiguousfilechannel

Java: READ and WRITE are "ambiguous" when using FileChannel with ByteChannel?


I am learning Java through an introductory course using the textbook, Java Programming 9th Edition by Joyce Farrel. The examples and exercises are written for Java 9e, however, I am using Java SE 14.

I've successfully navigated Java API and found updates as well as useful explanations as to what errors I have been encountering between the two versions and what is the best way to make corrections to get the examples and exercises to work.

However, in this case, I have been having a really hard time. I'm pretty sure it's due to the lack of experience, but I can't find anything I can understand using the Java API that has given me an idea on how to resolve this issue. Google and Stackoverflow posts have not been that much more successful as I am assuming people are using a much more streamlined method or approach.

Code with the comment on the line in question:

...
Path rafTest = Paths.get("raf.txt");
String addIn = "abc";
byte[] data = addIn.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
FileChannel fc = null;

try {
    fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); // Error READ and Write is ambiguous?
    ...
} catch (Exception e){
    System.out.println("Error message: " + e);
}
...

What is the best way to go about finding an approach to figuring out what exactly is going here?


Solution

  • @Bradley: Found the answer by trying to rewrite my question. The compiler returned 3 specific errors dealing with StandardOpenOption. Using that and Java API, I found the solution. Thank you.

    @NomadMaker: First thought was that I did not include the package correctly for newByteChannel. The second options were that the arguments needed a more specific reference.

    Answer: newByteChannel(...); requires the open options argument to reference the StandardOpenOption.READ and WRITE. So that:

    ...newByteChannel(raf, StandardOpenOption.READ, StandardOpenOption.WRITE);

    This change was implemented in Java SE 11. The program now works correctly.