读/写文件时出现异常

时间:2016-01-03 14:08:25

标签: java android inputstream android-contentprovider bufferedreader

我有两个Android应用程序,一个应用程序访问其他应用程序的内容提供程序,以便在从其他应用程序接收数据后访问某些文件。我尝试将其写入文件但获得异常。

以下是我的代码

private String getLog(String logFile)
{
    try {
        Uri fileUri = Uri.parse("content://" + AUTHORITY + "/" + logFile);
        ParcelFileDescriptor logFilePath = ControlApplication.getControlApplicationContext()
            .getContentResolver().openFileDescriptor(fileUri, "r");
        InputStream fileIs = new FileInputStream(logFilePath.getFileDescriptor());
        InputStreamReader tmp = new InputStreamReader(fileIs);
        BufferedReader reader = new BufferedReader(tmp);
        String str;
        StringBuffer buf = new StringBuffer();
        while ((str = reader.readLine()) != null) {
            buf.append(str + "\n");
        }
        fileIs.close();
        FileOutputStream outstream = ControlApplication.getControlApplicationContext()
            .openFileOutput(logFile, Context.MODE_PRIVATE);
        outstream.write(buf.toString().getBytes());
        outstream.close();

    }
    catch (Exception e) {
        Maas360Logger.e(loggerName, e, "Exception occured");
    }

    return logFile;
}

此处,logFile是其他应用程序中已存在的日志文件。这个文件我试图通过我的内容提供商。

即使我没有创建重复的目录,在从reader读取时会抛出以下异常:

01-03-2016 19:03:48.265 | E | AsyncTask #9 | DiagnosticServices | Exception occured
java.io.IOException: read failed: EISDIR (Is a directory)

Caused by: read failed: EISDIR (Is a directory)
at libcore.io.IoBridge.read(IoBridge.java:482)
at java.io.FileInputStream.read(FileInputStream.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:231)
at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
at java.io.BufferedReader.readLine(BufferedReader.java:397)

1 个答案:

答案 0 :(得分:1)

这里的问题是你在目录上尝试readLine

打印出"content://" + AUTHORITY + "/" + logFile的值,并确保这是您打算阅读的内容。

您还可以验证这是一个类似的目录:

File folder = new File("content://" + AUTHORITY + "/" + logFile");
boolean isDir = folder.isDirectory();

如果您想查看应在此目录中打开哪些文件,请尝试this answer