From 144550dd0ddfca23a5f5bade6acc5081cb855584 Mon Sep 17 00:00:00 2001 From: James Ahlborn Date: Fri, 25 Aug 2006 01:30:23 +0000 Subject: [PATCH] add support for opening files read-only (#1545857) git-svn-id: https://svn.code.sf.net/p/jackcess/code/jackcess/trunk@101 f203690c-595d-4dc9-a70b-905162fa7fd2 --- .../jackcess/Database.java | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/java/com/healthmarketscience/jackcess/Database.java b/src/java/com/healthmarketscience/jackcess/Database.java index fd90579..ed58aad 100644 --- a/src/java/com/healthmarketscience/jackcess/Database.java +++ b/src/java/com/healthmarketscience/jackcess/Database.java @@ -181,14 +181,29 @@ public class Database private Table _accessControlEntries; /** - * Open an existing Database + * Open an existing Database. If the existing file is not writeable, the + * file will be opened read-only. * @param mdbFile File containing the database */ public static Database open(File mdbFile) throws IOException { + return open(mdbFile, false); + } + + /** + * Open an existing Database. If the existing file is not writeable or the + * readOnly flag is true, the file will be opened read-only. + * @param mdbFile File containing the database + * @param readOnly iff true, force opening file in read-only + * mode + */ + public static Database open(File mdbFile, boolean readOnly) + throws IOException + { if(!mdbFile.exists() || !mdbFile.canRead()) { throw new FileNotFoundException("given file does not exist: " + mdbFile); } - return new Database(openChannel(mdbFile)); + return new Database(openChannel(mdbFile, + (mdbFile.canWrite() && !readOnly))); } /** @@ -197,15 +212,18 @@ public class Database * already exists, it will be overwritten. */ public static Database create(File mdbFile) throws IOException { - FileChannel channel = openChannel(mdbFile); + FileChannel channel = openChannel(mdbFile, true); channel.transferFrom(Channels.newChannel( Thread.currentThread().getContextClassLoader().getResourceAsStream( EMPTY_MDB)), 0, (long) Integer.MAX_VALUE); return new Database(channel); } - private static FileChannel openChannel(File mdbFile) throws FileNotFoundException { - return new RandomAccessFile(mdbFile, "rw").getChannel(); + private static FileChannel openChannel(File mdbFile, boolean needWrite) + throws FileNotFoundException + { + String mode = (needWrite ? "rw" : "r"); + return new RandomAccessFile(mdbFile, mode).getChannel(); } /** -- 2.39.5