gpt4 book ai didi

java - 创建文件并将其存储到外部存储

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

这对你来说可能是一个简单的破解方法,但我不明白为什么这段代码不会在我的 Android 外部文件系统中创建一个新文件?目录已正确创建,但文件未正确创建,而是我收到 java.io.FileNotFoundException:/mnt/sdcard/Mydir/MyFile,任何人都可以看到问题是什么,因为我看不到它吗?

        //Generate a unique filename using date and time
String fileName = "myFile_"+formatter_file_name.format(today)+".txt";

//Get path to root
String root = Environment.getExternalStorageDirectory().toString();

//Create(if not exists) directory in root in which to store the reports
File myDir = new File(root + "/myDir");
myDir.mkdirs();

//Create report file object
File file = new File (myDir, fileName);

//If file already exists delete id(this should not be able to happen)
if (file.exists()) file.delete();

try {
FileOutputStream fout = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fout);

// Write the string to the file
osw.write("TEST STRING");

//Ensure that everything has been written to the file and close
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
}

我的 list 中有正确的权限,我将插入一个检查以查看外部存储是否可用于写入,但我不认为这是问题...

最佳答案

试试这个

try {
File root = Environment.getExternalStorageDirectory();
File myFile = new File(root +"/textfile.txt");
myFile.createNewFile();

FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("String entered in file");

myOutWriter.close();
fOut.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();

}

关于java - 创建文件并将其存储到外部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13198563/

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