我正在尝试在 Android 中写入文本文件。我的代码如下(在服务中运行):
File log; String state = Environment.getExternalStorageState();
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
log = new File(path, "log.csv");
System.out.println("Opening file");
} else {
System.err.println("Could not write to external storage medium. No log will be created");
return;
}
String line = "stuff";
if (!log.exists()) {
try {
log.createNewFile();
System.out.println("Creating new log file.");
} catch (IOException e) {
System.err.println("Could not create new log file");
e.printStackTrace();
return;
}
}
try {
path.mkdirs();
BufferedWriter bw = new BufferedWriter(new FileWriter(log, true));
bw.append(line);
System.out.println("Appending to log file.");
bw.newLine();
bw.flush();
bw.close();
} catch (IOException e) {
System.err.println("Failed to write to log file");
e.printStackTrace();
return;
}
我在 AndroidManifest.xml 中添加了以下行:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
当我运行它时,LogCat 中会打印以下内容:
Opening file
Appending to log file.
但是我在手机内存中找不到任何具有给定名称的文件,尽管查看了所需的目录并运行搜索以查看它是否在其他地方。
我不确定可能出了什么问题。有任何想法吗?谢谢!