只是想我会更新至少部分答案。至少我的一些问题与在我的 Razr Maxx 上的调试模式下进行测试有关。当我通过 USB 调试连接时,创建新文件的调用失败,如下所示:
06-06 10:04:30.512: W/System.err(2583): java.io.IOException: 打开失败: EACCES (权限被拒绝) 06-06 10:04:30.512: W/System.err(2583):在 java.io.File.createNewFile(File.java:940)
当我在我的设备或模拟器上独立运行该应用程序时,它会按预期工作。不确定这是否与 Razr Maxx 或其他问题有关?
我的工作代码是(来自:Write a file in external storage in Android):
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
mStatusTV.append("\nExternal file system root: "+root);
// See https://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
file.createNewFile();
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
mStatusTV.append("Write File 1: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
mStatusTV.append("Write File 2: " + e.getMessage());
}
mStatusTV.append("\n\nFile written to "+file);
}