簡體   English   中英

無法寫入文件 - 為什么?

[英]Unable to write to file - why?

我正在嘗試保存到 android 中的長期文件存儲,並在此過程中創建一個新文件。 此代碼不斷崩潰,並使用最少的有用 logcat。

謝謝。

public void save (String text) {
    FileOutputStream fos = null;
    try {
        fos = openFileOutput("logfile.txt", MODE_PRIVATE);
        fos.write(text.getBytes());
    } catch (FileNotFoundException e)
    {} catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fos != null)
        {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

我希望它創建一個名為 logfile.txt 的文件並向其打印文本,但它卻崩潰了。

您需要清單中的文件寫入權限,並在運行時(作為彈出窗口)(再次)請求它。 這是假設您使用外部存儲。 你做了這個了嗎?

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
if (ContextCompat.checkSelfPermission(getActivity(),  Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x11);
                    } else Log.d("TAG", "permission already granted");

嘗試類似的方法,以便從 tmp / 私有存儲中的File中獲取FileOutputStream

// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);

結果路徑應該是/data/data/tld.domain.package/files/logfile.txt

file.getAbsolutePath()具有值。

請參閱在內部存儲上保存文件

暫無
暫無

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

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