gpt4 book ai didi

java - 在指定目录创建文件

转载 作者:太空狗 更新时间:2023-10-29 13:32:50 25 4
gpt4 key购买 nike

尝试在特定目录中创建文件,但显示错误 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/

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