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()方法不被识别。 有什么解决办法吗?


当前回答

如果你用的是Activity以外的类,你可能会想,

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));

其他回答

迟到总比不到好。

在某些情况下,我很难逐行阅读文件。 下面的方法是到目前为止我发现的最好的方法,我推荐它。

使用:字符串yourData = LoadData(“YourDataFile.txt”);

YourDataFile.txt假定驻留在资产/

 public String LoadData(String inFile) {
        String tContents = "";

    try {
        InputStream stream = getAssets().open(inFile);

        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        tContents = new String(buffer);
    } catch (IOException e) {
        // Handle exceptions here
    }

    return tContents;

 }

您可以从文件中加载内容。考虑文件在资产文件夹中。

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中

getAssets()

它只适用于其他任何类的活动,你必须为它使用上下文。

让Utils类的构造函数将活动引用(丑陋的方式)或应用程序上下文作为参数传递给它。在Utils类中使用getAsset()。

这里是一种方法来获得一个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;
}