Winson | 9947f1e | 2019-08-16 10:20:39 -0700 | [diff] [blame] | 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 android.content.res.loader; |
| 18 | |
| 19 | import android.annotation.NonNull; |
| 20 | import android.annotation.Nullable; |
| 21 | import android.os.ParcelFileDescriptor; |
| 22 | |
| 23 | import java.io.File; |
| 24 | import java.io.FileInputStream; |
| 25 | import java.io.IOException; |
| 26 | import java.io.InputStream; |
| 27 | |
| 28 | /** |
| 29 | * A {@link ResourceLoader} that searches a directory for assets. |
| 30 | * |
| 31 | * Assumes that resource paths are resolvable child paths of the directory passed in. |
| 32 | */ |
| 33 | public class DirectoryResourceLoader implements ResourceLoader { |
| 34 | |
| 35 | @NonNull |
| 36 | private final File mDirectory; |
| 37 | |
| 38 | public DirectoryResourceLoader(@NonNull File directory) { |
| 39 | this.mDirectory = directory; |
| 40 | } |
| 41 | |
| 42 | @Nullable |
| 43 | @Override |
| 44 | public InputStream loadAsset(@NonNull String path, int accessMode) throws IOException { |
| 45 | File file = findFile(path); |
| 46 | if (file == null || !file.exists()) { |
| 47 | return null; |
| 48 | } |
| 49 | return new FileInputStream(file); |
| 50 | } |
| 51 | |
| 52 | @Nullable |
| 53 | @Override |
| 54 | public ParcelFileDescriptor loadAssetFd(@NonNull String path) throws IOException { |
| 55 | File file = findFile(path); |
| 56 | if (file == null || !file.exists()) { |
| 57 | return null; |
| 58 | } |
| 59 | return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Find the file for the given path encoded into the resource table. |
| 64 | */ |
| 65 | @Nullable |
| 66 | public File findFile(@NonNull String path) { |
| 67 | return mDirectory.toPath().resolve(path).toFile(); |
| 68 | } |
| 69 | |
| 70 | @NonNull |
| 71 | public File getDirectory() { |
| 72 | return mDirectory; |
| 73 | } |
| 74 | } |