blob: 7d90e72ab07e61792170cc9bc5cff9017cc587e2 [file] [log] [blame]
Winson9947f1e2019-08-16 10:20:39 -07001/*
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
17package android.content.res.loader;
18
19import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.os.ParcelFileDescriptor;
22
23import java.io.File;
24import java.io.FileInputStream;
25import java.io.IOException;
26import 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 */
33public 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}