簡體   English   中英

應用程序不會將文件寫入內部存儲 [Android]

[英]Application does not write file to internal storage [Android]

我正在嘗試在 Android 中創建然后編寫一個名為“thisisafile.txt”的簡單文件。 運行應用程序后,文件在內部存儲中不存在。

import java.io.*;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String fileName = "thisisafile.txt";
    writeFile(fileName, "Hello World!");
}

    public static void writeFile(String fileName, String text) {
        File file = new File (fileName);
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(text);
        out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

文件寫好了嗎? 如果然后在哪里,因為我找不到它。 如果沒有,我在代碼中做錯了什么?

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

需要對清單的讀/寫權限,允許存儲權限。

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

參考資料:

https://developer.android.com/training/permissions/requesting#java https://stackoverflow.com/a/44155064/5207684

對文件使用以下路徑。 它會將文件寫入您的存儲根文件夾。

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");

writeToFile("File content".getBytes(), file);

寫入文件

public static void writeToFile(byte[] data, File file) throws IOException {

    BufferedOutputStream bos = null;

    try {
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data);
    }
    finally {
        if (bos != null) {
            try {
                bos.flush ();
                bos.close ();
            }
            catch (Exception e) {
            }
        }
    }
}

在清單中添加外部存儲寫入和讀取權限:

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

Android 6.0 后 WRITE_EXTERNAL_STORAGE 權限必須在運行時請求

requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);

然后可以在從它調用的活動中的 onRequestPermissionsResult() 方法中處理權限請求的結果。

例子:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

檢查真實設備而不是模擬器。

暫無
暫無

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

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