gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:05:05 24 4
gpt4 key购买 nike

我想在"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)"

我做错了什么?

更新:

list

<?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);

最佳答案

给你,

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

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

 filesDir = MainApplication.this.getFilesDir();

关于java - 我无法在项目内部目录中创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59576341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com