简体   繁体   English

Android Java从res / raw读取文本文件,找不到文件错误

[英]Android Java Reading a Text file from res/raw , file not found error

I am trying to read a text file that is stored under res/raw . 我正在尝试读取存储在res / raw下的文本文件。 I cannot workout why the file will not open and read the contents to the textArea " usersTextArea ". 我无法解析为什么文件无法打开并将内容读取到textArea“ usersTextArea ”。 The system just outputs System.out.println("file could not open"); 系统只输出System.out.println("file could not open"); . I don't think the file path is incorrect. 我不认为文件路径不正确。 Anyone know what could be causing the problem? 有谁知道可能导致问题的原因是什么? Thanks. 谢谢。

public void readFile()
{        
    String path = "android.resource://" + getPackageName() + "/" + R.raw.users;

    try
    {
        Scanner s = new Scanner(new File(path));

        while (scan.hasNext())
        {
            String data = scan.next();
            usersTextArea.append(data);
        }
        scan.close();
    }
    catch(Exception error)
    {
        System.out.println("file could not open");
    }
}

您可以访问以下原始资源:

getResources().openRawResource(R.raw.users)

You should try something like: 你应该尝试类似的东西:

public void readFile() {
    final InputStream input = getResources().openRawResource(R.raw.users);
    final Scanner scanner = new Scanner(input);
    try {
        // read the file
    } finally {
        // don't forget to close the resources, once you are done with them
        scanner.close();
        input.close();
    }
}

provide Read/Write permission in manifest file 提供清单文件中的读/写权限

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

then you can read res/raw file 那么你可以阅读res / raw文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM