gpt4 book ai didi

android - 尝试在 Android 中创建文件时出现 FileNotFoundException

转载 作者:太空狗 更新时间:2023-10-29 16:31:15 24 4
gpt4 key购买 nike

我正在尝试使用 Jexcel API 创建一个 excel 文件并使用我手机上的应用程序写入该文件。当我运行该应用程序时,它会抛出一个 FileNotFoundException。我什至尝试根据另一个此类问题的答案创建一个文本文件,但它会引发相同的错误。我已经在 list 中提供了适当的权限,但我似乎仍然无法查明问题所在。请帮忙。

这是我的代码

 public WritableWorkbook createWorkbook(String fileName){

//Saving file in external storage
File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File directory = new File(sdCard.getAbsolutePath() + "/bills");

//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
}

//file path
file= new File(directory, fileName);
if (file.exists())
Log.e(taf,"file created");
else
Log.e(taf,"file not created");

WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
wbSettings.setUseTemporaryFileDuringWrite(true);
WritableWorkbook workbook;
workbook=null;

try {
workbook = Workbook.createWorkbook(file, wbSettings);
Log.i(taf,"workbook created");
//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("MyShoppingList", 0);

try {
sheet.addCell(new Label(0, 0, "Subject")); // column and row
sheet.addCell(new Label(1, 0, "Description"));


String title = "blaj";
String desc = "nxjdncj";

int i = 1;
sheet.addCell(new Label(0, i, title));
sheet.addCell(new Label(1, i, desc));
} catch (WriteException e) {
e.printStackTrace();
}
workbook.write();
try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}

执行时,会打印日志消息“文件未创建”。我是 android 的新手,所以即使是最基本的问题也请指出。

谢谢。

最佳答案

实例化 File 不会创建文件,只会为您提供一个 File 实例,无论是否存在具有该特定路径和文件名的文件。

查看构造函数源码:

public File(String dirPath, String name) {
if (name == null) {
throw new NullPointerException("name == null");
}
if (dirPath == null || dirPath.isEmpty()) {
this.path = fixSlashes(name);
} else if (name.isEmpty()) {
this.path = fixSlashes(dirPath);
} else {
this.path = fixSlashes(join(dirPath, name));
}
}

要实际创建文件,您可以执行以下操作:

if (!file.exists()) {
// file does not exist, create it
file.createNewFile();
}

关于android - 尝试在 Android 中创建文件时出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38178008/

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