首页 > 解决方案 > Android-如何创建一个新的可写文件?

问题描述

我有一个 jobIntentService ,它创建一个文件以在其中添加一些文本,但出现错误/data/user/0/com.example.projet/files/log.txt (Is a directory)。我不知道我做错了什么......这是我的代码:

public void ecritureLog(Context context) {

        File path = context.getFilesDir();
        File file = new File(path, "log.txt");

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                Log.d("Debug ecriture log", "exeption levée : " + e.getMessage());
            }
        }

        try {
            FileOutputStream stream = new FileOutputStream(file);
            stream.write("text-to-write".getBytes());
            stream.close();
        } catch (Exception e) {
            Log.d("Debug ecriture log", "exeption levée : " + e.getMessage());
        }
    }

此外,我想要的是一种日志文件,所以我想从手机访问它,但它/data/user/0/com.example.projet/files/log.txt是用户的隐藏路径......我已经尝试过Environment.getDataDirectory(),但即使它们在清单中,我也没有权限。 ..

编辑:这是我的清单权限:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

谢谢你的帮助 !

标签: javaandroidandroid-studio

解决方案


With all the comment of you guys this work so there is the final code :

public void ecritureLog(Context context) {

        File path = context.getExternalFilesDir(null);
        File file = new File(path, "/log.txt");

        if (file.exists() && file.isDirectory() ) {
            if (!file.delete()){
                Log.d("Debug ecriture log", "!file.delete()");
                return;
            }
        }

        try {
            FileOutputStream stream = new FileOutputStream(file);
            Log.d("Debug ecriture log", "chemin: " +file.getAbsolutePath());
            stream.write("text-to-write".getBytes());
            stream.close();
        } catch (Exception e) {
            Log.d("Debug ecriture log", "exeption levée : " + e.getMessage());
        }
    }

Thanks !


推荐阅读