• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.google.android.libraries.mobiledatadownload.file.openers;
17 
18 import com.google.android.libraries.mobiledatadownload.file.OpenContext;
19 import com.google.android.libraries.mobiledatadownload.file.Opener;
20 import com.google.common.io.Files;
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.RandomAccessFile;
24 
25 /** Opener that returns a RandomAccessFile. */
26 public final class RandomAccessFileOpener implements Opener<RandomAccessFile> {
27 
28   private final boolean writeSupport;
29 
30   /**
31    * If writeSupport is false, the RAF is read only. If writeSupport is enabled, the RAF is read and
32    * write, and the directory is created if necessary.
33    */
RandomAccessFileOpener(boolean writeSupport)34   private RandomAccessFileOpener(boolean writeSupport) {
35     this.writeSupport = writeSupport;
36   }
37 
createForRead()38   public static RandomAccessFileOpener createForRead() {
39     return new RandomAccessFileOpener(/* writeSupport= */ false);
40   }
41 
42   /**
43    * Create an opener that returns a RandomAccessFile opened for read and write. If the File or its
44    * parent directories do not exist, they will be created.
45    */
createForReadWrite()46   public static RandomAccessFileOpener createForReadWrite() {
47     return new RandomAccessFileOpener(/* writeSupport= */ true);
48   }
49 
50   @Override
open(OpenContext openContext)51   public RandomAccessFile open(OpenContext openContext) throws IOException {
52     if (writeSupport) {
53       ReadFileOpener readFileOpener = ReadFileOpener.create().withShortCircuit();
54       File file = readFileOpener.open(openContext);
55       Files.createParentDirs(file);
56       return new RandomAccessFile(file, "rw");
57     } else /* if (!writeSupport) */ {
58       ReadFileOpener readFileOpener = ReadFileOpener.create();
59       File file = readFileOpener.open(openContext);
60       return new RandomAccessFile(file, "r");
61     }
62   }
63 }
64