在android上编写文件是不可能的

问题描述 投票:1回答:1

我使用以下代码将一些东西写入外部文件:

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();
        }
    }
}

另外,我的Manifest我添加了以下权限:

<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)

我在我的设备上使用Android 9(Oneplus 6T)并且它没有root或类似的东西。

java android android-external-storage
1个回答
0
投票

您需要请求在外部存储上写入的权限。仅将其列入清单是不够的。

请在此处查看权限系统的说明:https://developer.android.com/guide/topics/permissions/overview

有关如何请求权限的信息,请参阅https://developer.android.com/training/permissions/requesting.html

© www.soinside.com 2019 - 2024. All rights reserved.