Skip to content

Commit

Permalink
FileHandle: infer mode based on file permissions
Browse files Browse the repository at this point in the history
Instead of always trying read/write, which throws an exception
for existing but read-only files.
  • Loading branch information
ctrueden committed Apr 27, 2021
1 parent 46ca0d0 commit c4cb3a7
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/main/java/org/scijava/io/handle/FileHandle.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@

package org.scijava.io.handle;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;

import org.scijava.io.location.FileLocation;
Expand All @@ -50,7 +53,7 @@ public class FileHandle extends AbstractDataHandle<FileLocation> {
private RandomAccessFile raf;

/** The mode of the {@link RandomAccessFile}. */
private String mode = "rw";
private String mode;

/** True iff the {@link #close()} has already been called. */
private boolean closed;
Expand Down Expand Up @@ -232,6 +235,28 @@ public synchronized void close() throws IOException {
closed = true;
}

// -- WrapperPlugin methods --

@Override
public void set(FileLocation loc) {
super.set(loc);

// Infer the initial mode based on file existence + permissions.
final File file = loc.getFile();
String mode;
if (file.exists()) {
final Path path = loc.getFile().toPath();
mode = "";
if (Files.isReadable(path)) mode += "r";
if (Files.isWritable(path)) mode += "w";
}
else {
// Non-existent file; assume the intent is to create it.
mode = "rw";
}
setMode(mode);
}

// -- Typed methods --

@Override
Expand Down

0 comments on commit c4cb3a7

Please sign in to comment.