java - 使用存储在 ASSETS 文件夹中的文本文件

标签 java android assets

我试图了解存储在 assets 文件夹中的数据文件与存储在 res/raw 文件夹中的数据文件之间的区别。我的目标是将数据文件存储在 app 目录结构中,其中(在本例中)存储测试分数,可以访问它们,然后可以修改它们。据我了解,为此我需要使用 ASSET 而不是 RAW 文件。

当文本文件存储在 RES/RAW 文件夹中时,我设法将文本文件中的数据加载到数组中,但现在我使用的是 ASSET 文件,无法使其工作。我认为这就像使用 AssetManager.open 一样简单。

最终我的一个问题是这个。如何读取和写入 ASSET 文件夹中的文本文件?

这是我的代码:

public class MainActivity extends AppCompatActivity {

    String[][] testScoreList = new String[3][3];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Load test scores into arraylist
        nameArrayListMethod();
    }

   //This method loads test scores into an array
    public void nameArrayListMethod (){
        InputStreamReader InputSR = null;
        BufferedReader BufferedRdr = null;
        String thisLine = null;

        AssetManager am = getAssets();

        InputSR = new InputStreamReader(am.open("test_scores.txt"));
        BufferedRdr = new BufferedReader(InputSR);


        try {
            // open input stream test_scores for reading purpose.
            int i = 0;
            while ((thisLine = BufferedRdr.readLine()) != null) {
                // System.out.println(thisLine);

                String[] parts = thisLine.split(" ");
                testScoreList[i][0] = parts[0];
                testScoreList[i][1] = parts[1];
                i = i +1;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

我在 (am.open("test_scores.txt")) 行收到一个 Unhandled exception: java.io.IOException 错误。

为输入干杯

最佳答案

AssetManger#open(String) 会抛出异常,您需要处理它。

public final InputStream open(String fileName) throws IOException {
    return open(fileName, ACCESS_STREAMING);
}

所以你需要:

   try {
        InputSR = new InputStreamReader(am.open("test_scores.txt"));
        BufferedRdr = new BufferedReader(InputSR);
        // open input stream test_scores for reading purpose.
        int i = 0;
        while ((thisLine = BufferedRdr.readLine()) != null) {
            // System.out.println(thisLine);

            String[] parts = thisLine.split(" ");
            testScoreList[i][0] = parts[0];
            testScoreList[i][1] = parts[1];
            i = i +1;
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

关于java - 使用存储在 ASSETS 文件夹中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960935/

相关文章:

android - 如何覆盖 Phonegap webview 的方法?

ios - 使用 HTML 5 和 IOS 资源

android - Flutter Assets 中的多分辨率背景图像

java - 2018年雅虎邮箱Imap登录

java - 这是使用instanceof的情况吗?

java - 通过套接字以字节形式传输图像数据时,我不断收到 UTF 错误

android - 如何通过 Retrofit 解析带有未知 key 的 json?

java - java中的树状数据结构

java - 如何处理过时的连接?

php - Symfony2 assets 按文件版本控制