Android 某些手机正在获取java.io.FileNotFoundException,但为什么?

Android 某些手机正在获取java.io.FileNotFoundException,但为什么?,android,Android,我的应用程序中有自定义日志功能,代码如下 private boolean ready = false; private File logFile1 = null; private File logFile2 = null; private String filePath1,filePath2,filePath3; public NanoLog(int maxBytes) { try { String sdcard_status = Environment.get

我的应用程序中有自定义日志功能,代码如下

private boolean ready = false;
private File logFile1 = null;
private File logFile2 = null;
private String filePath1,filePath2,filePath3;

public NanoLog(int maxBytes)
{
    try
    {
        String sdcard_status = Environment.getExternalStorageState();
        if(sdcard_status.equals(Environment.MEDIA_MOUNTED) == false)
        {
            return;
        }
        String targetFolder = Environment.getExternalStorageDirectory().toString() + File.separator + "imadoco_log";
        File folder = new File(targetFolder);
        if(folder.exists() == false && folder.mkdir() == false)
        {
            return;
        }
        filePath1 = targetFolder + File.separator + "log1.txt";
        filePath2 = targetFolder + File.separator + "log2.txt";
        filePath3 = targetFolder + File.separator + "log.txt";
        logFile1 = new File(filePath1);
        logFile2 = new File(filePath2);
        if(logFile1.exists() == false)
        {
            logFile1.createNewFile();
        }
        else
        {
            limitBytes(maxBytes);
        }
        ready = true;
    }
    catch(Exception e)
    {
        ACRA.getErrorReporter().handleException(e);
    }
}

public synchronized void put(String text)
{
    if(ready)
    {
        try
        {
            BufferedWriter bw = new BufferedWriter(new FileWriter(logFile1,true));
            bw.append(text);
            bw.newLine();
            bw.close();
        }
        catch(IOException e)
        {
            ACRA.getErrorReporter().handleException(e);
            ready = false;
        }
    }
}
类NanoLog用于将调试跟踪写入文件。上面代码的重要部分是准备文件夹和写入文件

我的应用程序在某些手机上出现以下异常。大多数手机都能正常工作,所以我相信问题不是由清单文件中的权限引起的

  • java.io.FileNotFoundException:/mnt/sdcard/imadoco_log/log1.txt(权限被拒绝)
  • java.io.FileNotFoundException:/storage/sdcard0/imadoco_log/log1.txt:open failed:EROFS(只读文件系统)
  • java.io.FileNotFoundException:/storage/emulated/0/imadoco_log/log1.txt:open failed:EACCES(权限被拒绝)
说清楚一点,我有这个许可

android.permission.WRITE_EXTERNAL_STORAGE
我从ACRA的事故报告中找到了他们。它们在下一行代码中被捕获

BufferedWriter bw = new BufferedWriter(new FileWriter(logFile1,true));
我不明白为什么有些手机会出现这些例外。若在构造函数中检测到错误,函数put()将不会尝试写入文件


有什么想法吗?

您不仅应该检查要写入的文件夹是否存在,还应该检查该文件夹是否可写入。在上面使用File:canWrite()

您没有检查返回值。所以你不知道它是否成功


但无论如何,你最好不要用那种说法。新的Filewriter会注意这一点。

我认为您还应该在
put
方法中检查sd卡状态,而不仅仅是在构造函数中。考虑对象实例化和实际调用之间的时间:<代码> PUT/<代码>方法,同时会发生什么?看看这个:“Dusan,是的,我需要考虑一下这种情况。”但我不确定这样做是否能阻止这个问题的发生。我想如果logFile1.createNewFile()失败,那么它会抛出IOException,但文档说它不会一直发生,所以我最好检查一下。我会和File#canWrite()一起检查,看看会发生什么。
logFile1.createNewFile();