从内部存储读取txt文件会返回FIleNotFound,即使该文件位于该地址

时间:2018-09-25 09:16:31

标签: android file-handling internal-storage

我正在尝试从内部存储读取文件。该文件可在给定位置的内部存储中使用,并且代码能够访问它。.但是,当尝试打开文件时,它抛出FileNotFound Exception,这是由于该应用无法打开文件以进行读取。我通过使用file.canRead()返回错误的方法来了解应用程序无法打开文件。有人可以帮我弄清楚情况吗?这是我的代码

path = MainActivity.this.getFilesDir().getAbsolutePath();
try {
        File file = new File(path, "jamshaid.txt");
        Context ctx = getApplicationContext();
        FileInputStream fileInputStream = ctx.openFileInput(file.getName());
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String lineData = bufferedReader.readLine();
        view1.setText(lineData);

    } catch (Exception e) {
        e.printStackTrace();
    }

权限

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

  

我设备的API版本是24

我想做什么?

我正在尝试将文件/设置文本文件数据解析为textView

Update1

更改后
            File directory = MainActivity.this.getFilesDir(); File file = new File(directory, "jamshaid.txt");
我收到以下错误

`09-25 14:45:16.413 21144-21144/com.example.root.testingvolley     W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.root.testingvolley/files/jamshaid.txt (No such file or directory)`

2 个答案:

答案 0 :(得分:1)

尝试使用此作为目录路径

File directory = context.getFilesDir();
File file = new File(directory, filename);

public String getTextFileData(String fileName) {

        StringBuilder text = new StringBuilder();


        try {


         FileInputStream fIS = getApplicationContext().openFileInput(fileName);
         InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
         BufferedReader br = new BufferedReader(isr);

            String line;

            while ((line = br.readLine()) != null) {
                text.append(line + '\n');
            }
            br.close();
        } catch (IOException e) {
            Log.e("Error!", "Error occured while reading text file from Internal Storage!");

        }

        return text.toString();

    }

答案 1 :(得分:0)

您如何验证文件存在?也许文件不存在,在这种情况下,openFileInput()将引发FileNotFoundException。

您可以尝试以写入模式打开文件,如果不存在该文件,则会创建一个文件。

FileOutputStream fileOutputStream = ctx.openFileOutput(file.getName(), ctx.MODE_PRIVATE);