尝试在特定目录中创建文件,但显示错误 FileNotFound。为什么? 我在使用不可能的路径吗?我真的不知道,但看起来代码应该可以工作。
String day=/1;
String zn="/zn";
File_name=zn
String root= Environment.getExternalStorageDirectory().toString();
File_path=root+day;
File file1 = new File(File_path,File_name);
file1.mkdirs();
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
fos.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
最佳答案
更改代码以在 sdcard 上创建文件
String root= Environment.getExternalStorageDirectory().getAbsolutePath();
String File_name = "File_name.Any_file_Extension(like txt,png etc)";
File file1 = new File(root+ File.separator + File_name);
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
在当前的你中,你还缺少带有文件名的文件扩展名,因此将 String zn
更改为 zn="/zn.txt";
并确保您已在 AndroidManifest.xml
中添加了 Sd 卡权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
关于java - 在指定目录创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13682086/