读取外部存储上的文件长度,但获取fileNotFoundException

时间:2017-03-02 11:25:16

标签: android filenotfoundexception fileinputstream

我有以下代码,可以在手机的“下载”文件夹中为csv文件创建一个FileInputStream。

我可以记录文件的长度,但它抛出了一个FileNotFoundException。

当我输出正确的长度时,这怎么可能?

感谢

String fileName = "Download/file1.csv";
        String path = Environment.getExternalStorageDirectory()+"/"+fileName;
        File file = new File(path);

        Log.e(TAG, "file length = " + file.length());


        FileInputStream fin = null;
        try {
            // create FileInputStream object
            fin = new FileInputStream(file);

            byte fileContent[] = new byte[(int)file.length()];

            // Reads up to certain bytes of data from this input stream into an array of bytes.
            fin.read(fileContent);
            //create string from byte array
            String s = new String(fileContent);
            Log.e(TAG, "fileData = " + s);
        }
        catch (FileNotFoundException e) {

            Log.e(TAG, "File not found" + e);
        }
        catch (IOException ioe) {

            Log.e(TAG, "Exception while reading file " + ioe);
        }
        finally {
            // close the streams using close method
            try {
                if (fin != null) {
                    fin.close();
                }
            }
            catch (IOException ioe) {
                System.out.println("Error while closing stream: " + ioe);
                Log.e(TAG, "Error while closing stream: " + ioe);
            }
        }

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>



03-02 11:16:21.922 10112-10112/cftagwriter.carefreegroup.com.cftagwriter E/WriteTagActivity: file length = 523
03-02 11:16:21.922 10112-10112/cftagwriter.carefreegroup.com.cftagwriter E/WriteTagActivity: File not foundjava.io.FileNotFoundException: /storage/emulated/0/Download/file1.csv: open failed: EACCES (Permission denied)

1 个答案:

答案 0 :(得分:0)

//Create folder first
String dirPath = Environment.getExternalStorageDirectory()+"/Download";
        File dir = new File(dirPath);
        dir.mkdir();

//Create File
        File file = new File(dir,"file1.csv");