问题
I am trying to read a list of exercises from a file Exercises.txt in my /assests
folder and I've found plenty of examples how to, but I keep getting the error "context cannot be resolved" and if I manage to fix that, then I get "Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor"
Here is my code:
class ChooseExercises extends ListActivity{
String[] exercises;
AssetManager am = context.getAssets(); //Error 1
InputStream inputStream = am.open("test.txt"); //Error 2
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_exercises);
}
}
Thank you all for assistance.
回答1:
Since there is nothing named context
, you cannot refer to it from a data member initializer.
So, start by moving your AssetManager
and subsequent data members into onCreate()
as local variables, and replace context.getAssets()
with just getAssets()
, and you will be in better shape.
class ChooseExercises extends ListActivity{
String[] exercises;
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_exercises);
AssetManager am = context.getAssets(); //Error 1
InputStream inputStream = am.open("test.txt"); //Error 2
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// TODO: actually use this stuff
}
}
Later, as you get more comfortable with Java and Android, move this disk I/O into a background thread.
回答2:
I think you forgot to use a try-catch construction.
Writing:
try{
FileOutputStream fos = getBaseContext().openFileOutput("fileName", Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject("content");
os.close();
}catch(Exception ex){
//do stuff if something goes wrong.
}finally{
//do stuff in the end.
}
Reading:
try{
FileInputStream fis = getBaseContext().openFileInput("filename");
ObjectInputStream is = new ObjectInputStream(fis);
Object s = (Object) is.readObject(); // Object must be String if you want to read a string.
is.close();
}catch(Exception ex){
//do stuff if something goes wrong.
}finally{
//do stuff in the end.
}
来源:https://stackoverflow.com/questions/18069646/android-read-a-file