无法在存储卡中创建文件

时间:2016-11-22 21:01:27

标签: java android database memory android-sdcard

我正在尝试在文件中写入数据并将其存储在数据库中。我在网上尝试了很多代码。但是,我无法写入数据。任何人都可以帮助我。截至目前,我正在使用以下代码。我声明了onClick =“writemessage”并在writemessage(View view)函数中使用了以下代码。我正在通过将手机连接到笔记本电脑来运行。任何人都可以帮助我。

    FileOutputStream fos = null;

  try {
        String filename = "abc.txt";
        String data = "Sensor data is found";
        File myFile = new File(Environment
                .getExternalStorageDirectory(), filename);
        if (!myFile.exists())
            myFile.createNewFile();
        byte[] data = string.getBytes();
        try {
            fos = new FileOutputStream(myFile);
            fos.write(data);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:0)

您是否已在清单文件中添加此权限并处理运行时权限。

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

答案 1 :(得分:0)

检查AndroidManifest.xml是否有此权限

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

并在您的活动处理运行时权限

private int REQUEST_WRITE_EXTERNAL_STORAGE = 1;

在SD卡上写入文件之前检查Write External Storage Permission

  if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }else {
     //Write Data to SD Card
    }

并覆盖onRequestPermission活动方法。

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                this.finish();
                Toast.makeText(this, "Permission is required.", Toast.LENGTH_LONG).show();
            }
            return;
        }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            break;

    }