我无法在项目内部目录中创建文件夹

时间:2020-01-03 09:50:50

标签: java android file android-studio filenotfoundexception

我想在 "Ocenki" 文件夹中创建 txt 文件

我写了一个应写入 stringbuffer 文件的代码:

try {
    FileOutputStream write =  new FileOutputStream(
        new File(
            context.getFilesDir() 
            + File.separator + "Ocenki" 
            + File.separator + url + ".txt")
    );

    String temp_write = stringBuffer.toString();

    write.write(temp_write.getBytes());
    write.close();
} catch (FileNotFoundException p) {
    p.printStackTrace();
} catch (IOException a) {
    a.printStackTrace();
}

方法 context.getFilesDir() 返回: "/data/user/0/com.example.kos/files"

变量url包含:"2019 - 2020"

代码中出现错误:

FileNotFoundException  
"java.io.FileNotFoundException: /data/user/0/com.example.kos/files/2019 - 2020.txt  
(No such file or directory)"

我该怎么办?

UPD:

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kos"
    android:versionCode="2"
    android:versionName="1.1.1">
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    ...

</manifest>

以下是权限请求:

 if(ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) context,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},3);
            if(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
               ActivityCompat.requestPermissions((Activity) context,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},3);

1 个答案:

答案 0 :(得分:0)

你在这里

re.findall

当我在应用程序类中使用该类时,您可以基于其上下文在任何类上使用此方法

try{

  System.out.println("File Path = " + MainApplication.getFileDirectory() + "/Ocenki" + "/" + fileName);
  File fileCreated = new File(MainApplication.getFileDirectory() + "/Ocenki" + "/" + fileName);
  if (fileCreated.exists()) {
    fileCreated.delete();
  }
  outputStream = new FileOutputStream(MainApplication.getFileDirectory() + "/Ocenki" + "/" + fileName);
  byte[] buffer = new byte[1024];
  int read;

  while ((read = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, read);
  }

  //inputStream.close();
  outputStream.flush();
  outputStream.close();
  }catch (IOException io){
  io.printStackTrace();
}



public static File getFileDirectory() {
 return filesDir;
}