在android中,如何在所需文件夹中的外部目录中写入文件。 我使用了以下编码,但它似乎没有用。
File r = Environment.getExternalStorageDirectory();
File oD = new File(root.getAbsolutePath() + File.separator + "web_dir");
if (!outDir.isDirectory()) {
outDir.mkdir();
}
try {
if (!outDir.isDirectory()) {
throw new IOException(
"Unable to create directory");
}
File outputFile = new File(outDir, "web_file");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
writer.write(new String("hello"));
Toast.makeText(context.getApplicationContext(),
"Successfully saved to: " + outputFile.getAbsolutePath(),
Toast.LENGTH_LONG).show();
writer.close();
} catch (IOException e) {
Log.w("et", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external"
+"storage.", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:0)
错误讯息是什么?正如迈克所说,你可能错过了正确的许可。将以下内容添加到您的清单中,作为<manifest>
代码的子代:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:0)
首先确保您在清单文件中拥有写入外部存储空间的权限。
<!-- Depends on your requirements -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
参考:Saving Files - Android Developer Doc
下面的是将文件写入外部存储的示例代码。
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();
tv.append("\nExternal file system root: "+root);
// See http://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 {
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?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
希望它会帮助你..