I did some reading on the API for File IO and read the following blog post: http://techknock.blogspot.com/2008/05/file-hadling-in-android.html. His code works fine when everything is in the same activity. But what I am trying to do is create an IOInterface class that I can use to open multiple databases to populate multiple lists.
ListA.java
public class ListA
{
pu开发者_Python百科blic List<ClassA> list;
private final String DBA = "dbA";
private IOInterface database;
public List()
{
list = new ArrayList<ClassA>();
database = new IOInterface();
}
...
public void initListA() throws IOException
{
database.openForWriting(DBA);
String myStr = new String("content");
database.dos.writeBytes(myStr);
database.dos.flush();
database.dos.close();
}
}
IOInterface.java
public class IOInterface
{
public DataOutputStream dos;
private FileOutputStream fos;
public void openForWriting(String database)
{
try {
fos = openFileOutput(database, Content.MODE_PRIVATE);
dos = new DataOutputStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Eclipse underlines fos = openFileOutput(database, Content.MODE_PRIVATE);
. With the comment that openFileOutput()
does not exist. The resolution to this is to extend the IOInteface class as an Activity. I suppose then openFileOutput()
is a method of an activity class.
So my question is how do accomplish what I am trying to do? Standard Java file io such as:
File fp = new File("database");
FileOutputStream fos = new FileOutputStream(fp);
does not work. It catches a FileNotFoundException. This has to be doable though. Any ideas?
Thanks,
Method openFileOutput()
is contained in the Context
class, so you can pass an instance of this class to your method that opens files. And you should always use methods from Context
when you want to work with files.
You can read about using the internal and external storages in the development guide.
精彩评论