当我试图在Android Studio项目中读取一个二进制文件时,出现java.io.FileNotFoundException异常。

问题描述 投票:0回答:1

正如标题所说,我想读入一个二进制文件,"mac_address_name",这是已经创建的.该项目是在连接到android studio IDE的物理设备上运行的。

这是我的项目树,你可以看到类和二进制文件。

PROJECT TREE.PNG

下面是代码,在 处理器管理器 类,你可以在评论中看到我尝试的所有其他方法......

private String readFromFile() {

    String ret = "";

    try {

        /*InputStream inputStream = main_activity.getApplicationContext().openFileInput("mac_address_name");*/
        /*InputStream inputStream = new FileInputStream(new File("../mac_address_name"));*/
        /*InputStream inputStream = main_activity.openFileInput("mac_address_name");*/
        InputStream inputStream = new FileInputStream(new File("mac_address_name"));
        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

和输出。

Elogin活动。File not found: java.io.FileNotFoundException: mac_address_name: open failed: ENOENT (没有这样的文件或目录)

java android android-studio filenotfoundexception file-not-found
1个回答
1
投票

为了达到这个目的,你应该使用assets.Move该文件到你的项目中的srcmainassets文件夹,然后使用AssetsManager来获取文件内容。

AssetManager am = context.getAssets();
InputStream is = am.open("mac_address_name");

更多信息在。https:/nbasercode.comnetandroid-read-text-file-from-assets-folder-in-android-studio。https:/developer.android.comreferenceandroidcontentresAssetManager。

© www.soinside.com 2019 - 2024. All rights reserved.