我正在尝试写入Android的外部txt(或csv)文件。 我可以运行一个应用程序,将其关闭,然后再次运行,然后readData()会将已存储的内容读回到我的日志中。 但是,dirFile(文件目录)在我的Android文件中不显示(即使我将其连接到计算机并进行搜索)。
不过,有一点有趣的事情:如果我清除日志(类似于Eclipse中显示的打印语句列表)并断开手机与计算机的连接,然后重新连接,该日志就会以我曾经写入文件的所有内容重新出现(即使后来我改写了它)...但是该应用程序甚至没有运行!
这是我的代码。 请帮助我理解为什么找不到我的文件!
(注意:我尝试将“ myFile.txt”扩展名追加到目录中,但这只会导致EISDIR异常。)
public void writeData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Writes to file
//
// The "true" argument allows the file to be appended. Without this argument (just root),
// the file will be overwritten (even though we later call append) rather than appended to.
FileWriter writer = new FileWriter(root, true);
writer.append("Append This Text\n");
writer.flush();
writer.close();
// Checks if we actually wrote to file by reading it back in (appears in Log)
//readData(dirName);
}
catch(Exception e)
{
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
如果您有兴趣,这是我编写的读取数据的函数:
public void readData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Checks to see if we are actually writing to file by reading in the file
BufferedReader reader = new BufferedReader(new FileReader(root));
try {
String s = reader.readLine();
while (s != null) {
Log.v("2222", "2222 READ: " + s);
s = reader.readLine();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
finally {
reader.close();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
谢谢!