I'm trying to understand the difference between data files stored in the assets folder and those stored in the res/raw folder. My goal is to have a data file stored in the app directory structure where (in this case) test scores are stored, they can be accessed and then they can be modified. It is my understanding that I need to use an ASSET instead of RAW file for this.
I managed to load up the data from the text file into an array when the text file was stored in the RES/RAW folder but I can't make it work now that I'm using an ASSET file. I thought it was as easy as using AssetManager.open.
Ultimately my one question is this. How do I read and write to a text file in the ASSET folder?
Here is my code:
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();
}
I'm getting an Unhandled exception: java.io.IOException
eror on the (am.open("test_scores.txt"))
line.
Cheers for the input
AssetManger#open(String) will throw exception and you need handle it.
public final InputStream open(String fileName) throws IOException {
return open(fileName, ACCESS_STREAMING);
}
So you need:
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();
}