public class Utils {
public static List<Message> getMessages() {
//File file = new File("file:///android_asset/helloworld.txt");
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("helloworld.txt");
}
}
我正在使用这段代码试图从资产读取文件。我尝试了两种方法。首先,当使用文件时,我收到FileNotFoundException,当使用资产管理器getAssets()方法不被识别。
有什么解决办法吗?
您可以从文件中加载内容。考虑文件在资产文件夹中。
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
现在可以通过调用函数来获取内容,如下所示
String json= FileUtil.loadContentFromFile(context, "data.json");
考虑到数据。json存储在Application\app\src\main\assets\data.json中
这里是一种方法来获得一个InputStream的文件在资产文件夹没有上下文,活动,片段或应用程序。如何从InputStream中获取数据取决于您。在这里的其他答案中有很多关于这个问题的建议。
科特林
val inputStream = ClassLoader::class.java.classLoader?.getResourceAsStream("assets/your_file.ext")
Java
InputStream inputStream = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");
如果正在使用自定义ClassLoader,那么所有的赌注都是无效的。
ExceptionProof
It maybe too late but for the sake of others who look for the peachy answers.
loadAssetFile()方法返回资产的纯文本,如果有任何错误,则返回defaultValue参数。
public static String loadAssetFile(Context context, String fileName, String defaultValue) {
String result=defaultValue;
InputStreamReader inputStream=null;
BufferedReader bufferedReader=null;
try {
inputStream = new InputStreamReader(context.getAssets().open(fileName));
bufferedReader = new BufferedReader(inputStream);
StringBuilder out= new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
out.append(line);
line = bufferedReader.readLine();
}
result=out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Objects.requireNonNull(inputStream).close();
} catch (Exception e) {
e.printStackTrace();
}
try {
Objects.requireNonNull(bufferedReader).close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}