简体   繁体   中英

How to get right path files in android

My code is following::

Scanner sc = null;
try {
    sc = new Scanner(new File("assets/mainmenu/readSourceFile.txt"));
} catch (FileNotFoundException e1) {
    // TODO Auto-generated catch block
    System.out.println(e1.toString());
    e1.printStackTrace();
}

Then, logcat show exception java.io.FileNotFoundException

How can I find my file? I tried

sc = new Scanner(new File("mainmenu/readSourceFile.txt"));

However, it's still throw FilenotFoundException

My file is in folder assets/mainmenu/readSourceFile.txt

and I've try this::

private InputStream is;
try {
        is = this.getResources().getAssets().open("mainmenu/readSourceFile.txt");
    } catch (IOException e) {
        e.toString();
    }

I use getAssets to access assets file in android. However, how can I suppose to read text file if I use InputStream

You try this...Hope it will work

sc = new Scanner(new File("file:///android_asset/mainmenu/readSourceFile.txt");

Edit try this

AssetFileDescriptor descriptor = getAssets().openFd("mainmenu/readSourceFile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());

Copied from here Asset folder path

You can't access the assets folder of your Android application as if they were regular files on the file system (hint: they're not). Instead, you need to use AssetManager .Call getAssets() on your activity/application context to get the AssetManager .

Once you have this, you can use open("mainmenu/readSourceFile.txt") to obtain an InputStream .

You can now read this InputStream like you would any other. Apache Commons IO is a great library for working with input and output streams. Depending on how you want to get the data, you could try:

  • Read the entire file into a String:

     try { String contents = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); } 
  • Read the entire file into a list of Strings, one per line:

     try { List<String> lines = IOUtils.readLines(in); } finally { IOUtils.closeQuietly(in); } 
  • Iterate through the file one line at a time:

     try { LineIterator it = IOUtils.lineIterator(in, "UTF-8"); while (it.hasNext()) { String line = it.nextLine(); // do something with line } } finally { IOUtils.closeQuietly(in); } 

I had the same issue. I noticed that the file should not include the hierarchy. This worked for me if someone had the same issue in future. `

    InputStream is=null;

    try {
        is=activity.getAssets().open("fileInAssets.dat");
    } catch (IOException e1) {
        Log.e(TAG, "Erro while openning hosts file.");
        e1.printStackTrace();
    }

`

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.

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