简体   繁体   English

应用程序不会将文件写入内部存储 [Android]

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

I am trying to create and then write a simple file called "thisisafile.txt" in Android.我正在尝试在 Android 中创建然后编写一个名为“thisisafile.txt”的简单文件。 After I run the application, file does not exist in internal storage.运行应用程序后,文件在内部存储中不存在。

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

Is the file written?文件写好了吗? If then where, because I can't find it.如果然后在哪里,因为我找不到它。 If not, what am I doing wrong in the code?如果没有,我在代码中做错了什么?

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

Need Read / Write Permission On Manifest, Allow Storage Permission.需要对清单的读/写权限,允许存储权限。

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

Referrence:参考资料:

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

Use the following path for a file.对文件使用以下路径。 It will write file to your root folder of storage.它会将文件写入您的存储根文件夹。

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

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

writeToFile写入文件

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) {
            }
        }
    }
}

add external storage writing AND reading permissions in the manifest:在清单中添加外部存储写入和读取权限:

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

After Android 6.0 WRITE_EXTERNAL_STORAGE permission must request in run time Android 6.0 后 WRITE_EXTERNAL_STORAGE 权限必须在运行时请求

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

and then can handle the result of permission request in onRequestPermissionsResult() method inside activity called from it.然后可以在从它调用的活动中的 onRequestPermissionsResult() 方法中处理权限请求的结果。

Example:例子:

// 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
}

Check on real device instead of Emulator.检查真实设备而不是模拟器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM