I am trying to read a text file that is stored under res/raw . I cannot workout why the file will not open and read the contents to the textArea " usersTextArea
". The system just outputs 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.