我正在使用以下代码将一些内容写入外部文件:
public class DiskWriter {
public static String TAG = "DiskWriter";
public static void writeStringToDisk(String jsonString) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/JSONFolder");
dir.mkdirs();
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS");
File file = new File( dir, "/json-" + df.format(new Date(System.currentTimeMillis())) + ".txt");
Log.e(TAG, "Writing file to " + file.getAbsolutePath());
try {
file.createNewFile();
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(jsonString);
pw.flush();
pw.close();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
此外,在我的清单中,我添加了以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我还尝试了此代码的几种变体。但是,它永远都行不通。这是输出:
E/DiskWriter: Writing file to /storage/emulated/0/JSONFolder/json-20190306-190419.289.txt
W/System.err: java.io.IOException: No such file or directory
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
W/System.err: at java.io.File.createNewFile(File.java:1345)
W/System.err: at app.generic.logic.DiskWriter.writeStringToDisk(DiskWriter.java:28)
W/System.err: at app.generic.logic.JSONParser.doInBackground(JSONParser.java:48)
W/System.err: at app.generic.logic.JSONParser.doInBackground(JSONParser.java:36)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:764)
我在设备(Oneplus 6T)上使用的是Android 9,但它没有根目录或类似内容。
答案 0 :(得分:0)
您需要请求对外部存储进行写入的权限。仅将其列出在清单中是不够的。
在此处查看权限系统的说明:https://developer.android.com/guide/topics/permissions/overview
,有关如何请求权限的信息,请参见https://developer.android.com/training/permissions/requesting.html