2017-08-25 108 views
0

我使用JNI来开发我的应用程序,并且在C++层中有两个用作输入文件的.dat文件。目前,我打开相关的应用程序之前,通过adb将这两个文件推入移动设备。我认为有一个更好的解决方案可以防止将两个文件推入移动设备。如何和输入文件到apk可以从C++读取?

回答

0

尝试了几种解决方案后,我通过结合三种解决方案和下面显示的代码解决了这个问题。在使用代码之前,您需要创建一个名为“assets”的文件夹,与“res”文件夹平行。通过这种方式,您可以将您可能使用的输入文件附加到apk中,并且在第一次安装apk时,它会自动将文件存储到目标设备中的特定路径。

public class CameraPreviewActivity extends AppCompatActivity 
    implements CameraPermissionHelper.CameraPermissionCallback { 


SharedPreferences prefs = null; 


public static String TAG = "CameraPreviewActivity"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    prefs = getSharedPreferences("com.yourcompany.yourapp", MODE_PRIVATE); 

} 




@Override 
protected void onDestroy() { 
    super.onDestroy(); 

} 

@Override 
protected void onResume() { 
    super.onResume(); 

    if(prefs.getBoolean("firstrun", true)){ 
     prefs.edit().putBoolean("firstrun", false).commit(); 
     try { 
      final InputStream input = getResources().getAssets().open("face_model.dat"); 

      try { 
       File UPLOAD_DIR = new File("/sdcard"); 
       File file = new File(UPLOAD_DIR, "face_model.dat"); 
       OutputStream output = new FileOutputStream(file); 
       try { 
        try { 
         byte[] buffer = new byte[4 * 1024]; // or other buffer size 
         int read; 

         while ((read = input.read(buffer)) != -1) { 
          output.write(buffer, 0, read); 
         } 
         output.flush(); 
        } finally { 
         output.close(); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); // handle exception, define IOException and others 
       } 
      } finally { 
       input.close(); 
      } 

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

     try { 
      final InputStream input = getResources().getAssets().open("shape_pred.dat"); 

      try { 
       File UPLOAD_DIR = new File("/sdcard"); 
       File file = new File(UPLOAD_DIR, "shape_pred.dat"); 
       OutputStream output = new FileOutputStream(file); 
       try { 
        try { 
         byte[] buffer = new byte[4 * 1024]; // or other buffer size 
         int read; 

         while ((read = input.read(buffer)) != -1) { 
          output.write(buffer, 0, read); 
         } 
         output.flush(); 
        } finally { 
         output.close(); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); // handle exception, define IOException and others 
       } 
      } finally { 
       input.close(); 
      } 

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

}