1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 
17 package com.android.server.backup.utils;
18 
19 import static com.android.server.backup.BackupManagerService.TAG;
20 
21 import android.util.Slog;
22 
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.io.IOException;
26 import java.io.RandomAccessFile;
27 
28 /** Utility methods useful for working with backup related RandomAccessFiles. */
29 public final class RandomAccessFileUtils {
getRandomAccessFile(File file)30     private static RandomAccessFile getRandomAccessFile(File file) throws FileNotFoundException {
31         return new RandomAccessFile(file, "rwd");
32     }
33 
34     /** Write a boolean to a File by wrapping it using a RandomAccessFile. */
writeBoolean(File file, boolean b)35     public static void writeBoolean(File file, boolean b) {
36         try (RandomAccessFile af = getRandomAccessFile(file)) {
37             af.writeBoolean(b);
38         } catch (IOException e) {
39             Slog.w(TAG, "Error writing file:" + file.getAbsolutePath(), e);
40         }
41     }
42 
43     /** Read a boolean from a File by wrapping it using a RandomAccessFile. */
readBoolean(File file, boolean def)44     public static boolean readBoolean(File file, boolean def) {
45         try (RandomAccessFile af = getRandomAccessFile(file)) {
46             return af.readBoolean();
47         } catch (IOException e) {
48             Slog.w(TAG, "Error reading file:" + file.getAbsolutePath(), e);
49         }
50         return def;
51     }
52 }
53