【问题标题】:Cannot find the path of folder in the same directory location - Android studio在同一目录位置找不到文件夹的路径 - Android Studio
【发布时间】:2018-05-21 01:58:39
【问题描述】:

我将一个名为 profiles 的文件夹放在我的 java 文件存储的同一目录中。

我试图找到该文件夹​​,但得到一个未找到的错误。

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  " );
}

打印

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

然后我尝试列出该目录中的所有文件

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());
}

打印

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

我似乎在错误的目录中,因为我看不到这些文件。有什么建议吗?

【问题讨论】:

  • 我从未见过这样的用法。尝试将您的文件夹放入 assets 或 raw 中。
  • 如果我把文件放在assets里,我怎么能得到那个路径?
  • file:///android_asset/profiles/
  • 成功了吗?有什么问题吗?
  • 尚未成功。试。我只是尝试String path = "file:///android_asset/" 来查看所有文件。我收到 java.lang.NullPointerException 错误

标签: android file android-studio directory file-exists


【解决方案1】:

main 文件夹中创建assests 文件夹。将您的 profiles 文件夹放入 assets 文件夹中。要读取profiles 文件夹中的文件名,请使用此代码。

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

要从此文件夹中读取文件,请使用这个。

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

【讨论】:

  • 如果我可以看到所有使用getAssets().list("profiles") 的文件,为什么File folder = new File("file:///android_asset/profiles/"); 显示不存在?感谢您的帮助
  • 您只能将此路径用于url file:///android_asset/profiles/"。例如,您可以在 WebView 中使用它。
  • profiles 中有什么?你想用它们做什么。
  • 哦,我明白了。我需要调用路径来加载一些数据。 stackoverflow.com/a/22934175/5737856
  • 参数应该是FileString(路径)。我还尝试使用此函数将InputStream 转换为Filestackoverflow.com/a/11820891/5737856。但是得到一个java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File[] java.io.File.listFiles()' on a null object reference error。无论如何,感谢您的帮助。我需要休息一下。如果我以后弄清楚,我会投票给你的答案。谢谢。
猜你喜欢
  • 2014-04-12
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多