Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android open file

Tags:

file

android

I was trying to open a file for reading.

When using: Scanner input = new Scanner(filename); the file could not be found

but when I used:

InputStream in = openFileInput(filename);
Scanner input = new Scanner(in);

It worked. Why was the first line of code wrong?

like image 526
zSt Avatar asked Oct 12 '11 14:10

zSt


People also ask

Why can't I open files on my Android?

If a file won't open, a few things could be wrong: You don't have permission to view the file. You're signed in to a Google Account that doesn't have access. The correct app isn't installed on your phone.

How do I open internal files on Android?

But in most cases, you can see the internal storage of an Android phone: Navigate to My Files to view internal storage as well as SD card and Network storage. Here, tap Internal Storage to see your files and folders. Tap the DCIM folder to view your photos.

How do I select an app to open a file on Android?

With the file selected, open the File menu then choose Get info. Go down to Open with and choose your preferred app from the list. Once that's done, click Change All and confirm your choice on the pop-up dialog.

How do I open a file in Android 11?

Please go to Android system settings, find storage section, click it. From the storage page, find "Files" item, and click it. If there are multiple file managers to open it, please make sure to choose "Open with Files" to open it, which is the system file manager app.


1 Answers

Files are stored on the device in a specific, application-dependent location, which is what I suppose openFileInput adds at the beginning of the file name. The final result (location + file name) is constructed as follows:

/data/data/<application-package>/files/<file-name>

Note also that the documentation states that the openFileInput parameter cannot contain path separators.

To avoid hard-coding the location path, which could in principle even be different from device to device, you can obtain a File object pointing to the storage directory by calling getFilesDir, and use it to read whatever file you would like to. For example:

File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));

Note that constructing a Scanner by passing a String as a parameter would result in the scanner working on the content of the string, i.e. interpreting it as the actual content to scan instead of as the name of a file to open.

like image 196
Giulio Piancastelli Avatar answered Sep 28 '22 04:09

Giulio Piancastelli