在SD卡上创建新文件

时间:2019-03-17 20:57:49

标签: java android

我正在尝试在android studio中创建一个程序,该程序在sd卡上写入.txt文件/如果还没有一个文件,则创建一个新文件,但是它从未创建该文件,而且我一直在不断获取例外:

java.io.IOException:没有这样的文件或目录

这是我的代码:

public void write(String filename) throws IOException {
    EditText contentTxt = (EditText)findViewById(R.id.fileTxtField);
    String path = Environment.getExternalStorageDirectory().getPath()+"/Demo/"+filename;
    File file = new File(path);
    if(!file.exists())
    {
        file.getParentFile().mkdirs();
        file.createNewFile();
        new AlertDialog.Builder(this).setTitle("File Created").setMessage("File successfully created!").show();
    }

    PrintWriter out = new PrintWriter(new FileWriter(file, true));

    out.println(contentTxt.getText().toString());
    out.flush();
    out.close();
}

1 个答案:

答案 0 :(得分:2)

编辑:我测试了您的代码,它可以工作。您需要读写权限!

将这些添加到清单

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

进行权限检查,可能在构造函数中调用了函数。

public void checkWritePermissions(){
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Permission is not granted
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // 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(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); //1 is the requestCode
        }
    } else {
        // Permission has already been granted
        writeFile(); //Or maybe return a bool value, true or false
    }

}

下一步覆盖onRequestPermissionsResult函数/方法。在onCreate之外(显然)执行此操作

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 1: { //CODE 1
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // WRITE_EXTERNAL_STORAGE-related task you need to do.
                //Continue and write the file
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                //Maybe display a message or something
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request.
    }
}

对于您的代码,它的工作方式就像我说的那样,我只想更改一下它。

如果目录../Demo/不存在,则无法在其中创建文件,因此请确保先创建目录。您这样做的方式很好,但是它所做的工作超出了需要。

 //Lets make a new DIR
 if (!file.getParentFile().exists()){
   file.getParentFile().mkdirs();
 }

if(!file.exists())
{
    file.createNewFile();
    new AlertDialog.Builder(this).setTitle("File Created").setMessage("File successfully created!").show();
} 

希望有效! :)