写文件在Android中不工作 [英] Writing to file not working in Android
问题描述
我试图写在Android的一个文本文件中。我的code是如下(以服务运行):
I am trying to write to a text file in Android. My code is as follows (running in a Service):
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:
And I have put the following line in AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
当我运行此,下面是印在LogCat中:
When I run this, the following is printed in LogCat:
Opening file
Appending to log file.
但我不能找到在手机内存中的特定名称的任何文件,尽管在寻找所需的目录并运行一个搜索,看它是否是别的地方吧。
But I can't find any files with the given name on the phone's memory, despite looking in the desired directory and running a search to see if it's somewhere else instead.
我不知道有什么可以去错了。有任何想法吗?谢谢!
I'm not sure what could be going wrong. Any ideas? Thanks!
推荐答案
如果它是一个真正的设备(未AVD),那么我认为这是通过USB插入计算机。某些设置不允许,而它的插入到电脑上浏览外部存储。拔掉它,并查找文件。
If it's a real device (not AVD), then I think it's plugged into your computer via USB. Some settings doesn't allow to browse external storage while it's plugged to a computer. Unplug it, and look for the file.
这篇关于写文件在Android中不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!