gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:45:00 25 4
gpt4 key购买 nike

我试图了解存储在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com