当前位置: 代码迷 >> java >> 在Android Studio中加载文件
  详细解决方案

在Android Studio中加载文件

热度:122   发布时间:2023-07-17 20:10:41.0

我尝试了这里建议的解决方案: 中 。

我需要从活动类的外部加载文件,并且这些值将在其他各种类中使用。

(旁注,我不一定非要把这些文件放在资产文件夹中,它们可以在任何地方,只要我能以某种方式加载它们即可)。

基本上,它告诉我检查一个名为“ app.iml”的文件以包含以下行:

option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets"

是的。

之后,将文件添加到“资产”目录。

然后,我尝试使用以下方式加载文件:

File file = new File("IDs.txt");

Scanner in = new Scanner(file);

但是我得到了“找不到文件”异常。

无论我将文件放在何处,都无法加载它们。 有什么建议么?

答案已更新,并将文件复制到应用程序文件夹

您无法使用File f = new File从资产中打开文件。 您应该像这样打开资产:

File ids = new File(getExternalFilesDir("txt") + File.separator + "IDs.txt");
InputStream is = null;
    if (!ids.exists()) {
        AssetManager manager = getAssets();
        try {
            is = manager.open("IDs.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (is != null)
        try{
            OutputStream outputStream = new FileOutputStream(ids);
            byte buffer[] = new byte[1024];
            int length = 0;

            while ((length = is.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

现在,您可以将file或file_path设置为您的课程:

File ids = new File(getExternalFilesDir("txt") + File.separator + "IDs.txt");

要获取完整路径,请使用ids.getAbsolutePath();

  相关解决方案