Pak Ho Cheung
Pak Ho Cheung

Reputation: 1416

Cannot find the path of folder in the same directory location - Android studio

I drop a folder called profiles in the same directory where my java files stored.

enter image description here

I tried to find the folder but get a not-found error.

String dir = getApplicationInfo().dataDir;
Log.d("dir", dir);
File folder = new File("/profiles"); // also tried File folder = new File(dir+"/profiles");
if (!folder.exists()) {
    Log.d("Not Found Dir", "Not Found Dir  ");
} else {
    Log.d("Found Dir", "Found Dir  " );
}

Print

D/dir: /data/user/0/com.pakhocheung.o
D/Not Found Dir: Not Found Dir

Then I tried to list all the files in that directory

String path = dir;
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++) {
    Log.d("Files", "FileName:" + files[i].getName());
}

Print

D/Files: Path: /data/user/0/com.pakhocheung.o
D/Files: Size: 6
D/Files: FileName:cache
D/Files: FileName:code_cache
D/Files: FileName:lib
D/Files: FileName:shared_prefs
D/Files: FileName:app_Paas
D/Files: FileName:files

It seems I am in the wrong directory because I can't see those files. Any suggestions?

Upvotes: 1

Views: 1919

Answers (1)

Bek
Bek

Reputation: 8471

Create assests folder inside main folder. Put your profiles folder in assets folder. To read file names inside profiles folder use this code.

String[] list = null;
    try {
        list = getAssets().list("profiles");
        for (String file: list){
            Log.d(TAG, "file name "+ file.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

To read file from this folder use this.

InputStream is = getAssets().open("profiles/example.txt");

Upvotes: 2

Related Questions