簡體   English   中英

Android-如何創建一個新的可寫文件?

[英]Android-How to create a new writeable file?

我有一個 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" />

謝謝你的幫助 !

有了你們的所有評論,這項工作有了最終的代碼:

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

謝謝 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM