1 /*
2  * Copyright (C) 2021 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.uwb.util;
18 
19 import android.util.AtomicFile;
20 
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 
26 /**
27  * Utils created for working with {@link AtomicFile}.
28  */
29 public final class FileUtils {
FileUtils()30     private FileUtils() {}
31 
32     /**
33      * Read raw data from the atomic file.
34      * Note: This is a copy of {@link AtomicFile#readFully()} modified to use the passed in
35      * {@link InputStream} which was returned using {@link AtomicFile#openRead()}.
36      */
readFromAtomicFile(AtomicFile file)37     public static byte[] readFromAtomicFile(AtomicFile file) throws IOException {
38         FileInputStream stream = null;
39         try {
40             stream = file.openRead();
41             int pos = 0;
42             int avail = stream.available();
43             byte[] data = new byte[avail];
44             while (true) {
45                 int amt = stream.read(data, pos, data.length - pos);
46                 if (amt <= 0) {
47                     return data;
48                 }
49                 pos += amt;
50                 avail = stream.available();
51                 if (avail > data.length - pos) {
52                     byte[] newData = new byte[pos + avail];
53                     System.arraycopy(data, 0, newData, 0, pos);
54                     data = newData;
55                 }
56             }
57         } finally {
58             if (stream != null) stream.close();
59         }
60     }
61 
62     /**
63      * Write the raw data to the atomic file.
64      */
writeToAtomicFile(AtomicFile file, byte[] data)65     public static void writeToAtomicFile(AtomicFile file, byte[] data) throws IOException {
66         // Write the data to the atomic file.
67         FileOutputStream out = null;
68         try {
69             out = file.startWrite();
70             out.write(data);
71             file.finishWrite(out);
72         } catch (IOException e) {
73             if (out != null) {
74                 file.failWrite(out);
75             }
76             throw e;
77         }
78     }
79 }
80