在Android中尝试创建文件时出现FileNotFoundException错误

4
我尝试使用Jexcel API在我的手机应用程序中创建Excel文件并将其写入。当我运行应用程序时,它会抛出FileNotFoundException异常。我甚至根据另一个类似问题的答案尝试创建文本文件,但仍然会抛出相同的错误。我已在清单中给予了适当的权限,但仍然无法确定问题所在。请帮忙解决。
这是我的代码:
 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新手,请指出最基本的问题。

谢谢。


你的安卓版本是6.0吗? - Sohail Zahid
是的,它适用于棉花糖之前的设备。我已经阅读过对于棉花糖设备,您需要添加运行时权限,但我不确定如何添加这些权限。 - keshav johar
2个回答

7

实例化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();
}

0

你需要在下面再添加一行:

file= new File(directory, fileName);
file.createNewFile();// add this line

我希望你已经在清单文件中添加了权限。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接