Skip to content

Android-How to create a new writeable file?

I have a jobIntentService that create a file to add some text in it but I get the error /data/user/0/com.example.projet/files/log.txt (Is a directory). I don’t know what I did wrong… Here is my code :

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

Furthermore, what I want is a sort of log file so I want to access it from the phone but /data/user/0/com.example.projet/files/log.txt is an hidden path to the user… I already tried Environment.getDataDirectory() but I don’t have the permission even if they are in the manifest…

Edit : Here is my manifest permissions :

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

Thanks for your help !

Answer

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 !