Android open file

前端 未结 3 1937
北海茫月
北海茫月 2021-01-04 05:51

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:

相关标签:
3条回答
  • 2021-01-04 06:20

    This drove me crazy couple of minutes ago. I forgot to add this line to manifest:

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

    I would expect a permission denied message. But just got a file not found...

    In your case: openFileInput opens a file in your private app data directory (/data/data/your.package/filename). This never fails. But the scanner tries to open it on the root path. So when you want to read a file from SD card than you would use Environement.getExternalStorageDirectory().getAbsolutePath() + "/" + filename.

    0 讨论(0)
  • 2021-01-04 06:23

    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.

    0 讨论(0)
  • 2021-01-04 06:32
    Scanner sc = new Scanner(new File(filename));
    
    0 讨论(0)
提交回复
热议问题