Skip to content

Commit c4cb3a7

Browse files
committed
FileHandle: infer mode based on file permissions
Instead of always trying read/write, which throws an exception for existing but read-only files.
1 parent 46ca0d0 commit c4cb3a7

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/main/java/org/scijava/io/handle/FileHandle.java

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,11 @@
2929

3030
package org.scijava.io.handle;
3131

32+
import java.io.File;
3233
import java.io.IOException;
3334
import java.io.RandomAccessFile;
35+
import java.nio.file.Files;
36+
import java.nio.file.Path;
3437
import java.util.Date;
3538

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

5255
/** The mode of the {@link RandomAccessFile}. */
53-
private String mode = "rw";
56+
private String mode;
5457

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

238+
// -- WrapperPlugin methods --
239+
240+
@Override
241+
public void set(FileLocation loc) {
242+
super.set(loc);
243+
244+
// Infer the initial mode based on file existence + permissions.
245+
final File file = loc.getFile();
246+
String mode;
247+
if (file.exists()) {
248+
final Path path = loc.getFile().toPath();
249+
mode = "";
250+
if (Files.isReadable(path)) mode += "r";
251+
if (Files.isWritable(path)) mode += "w";
252+
}
253+
else {
254+
// Non-existent file; assume the intent is to create it.
255+
mode = "rw";
256+
}
257+
setMode(mode);
258+
}
259+
235260
// -- Typed methods --
236261

237262
@Override

0 commit comments

Comments
 (0)