2016-12-12 95 views
0

我试图获取应用程序的APK并将其保存在存储目录的文件夹中。我有apk但我无法将它保存到我想要的文件夹。如何将应用程序的apk文件写入文件夹

这里是我正在生成APK文件:

final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
    List<ResolveInfo> apps = getPackageManager().queryIntentActivities(mainIntent, 0); 

    for (ResolveInfo info : apps) { 
      File fileToSave = new File(info.activityInfo.applicationInfo.publicSourceDir) 
    } 

这里是保存在那里我传递了相同的文件保存APK文件的代码:

private void createDirectoryAndSaveFile(File fileToSave) { 
     try { 
      String folderName = "MyCreatedFolder"; 

      File folder = new File(Environment.getExternalStorageDirectory() + 
        File.separator + folderName); 
      boolean success = true; 
      if (!folder.exists()) { 
       success = folder.mkdirs(); 
      } 
      if (success) { 
       File path = new File(context.getFilesDir(), folderName); 
       File mypath = new File(path, fileToSave.getName()); 
       new BufferedWriter(new FileWriter(mypath)); 
       Toast.makeText(context, "Created", Toast.LENGTH_LONG).show(); 
      } else { 
       Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show(); 
      } 
     } catch (Exception e) { 
      System.out.println("----" + e.getLocalizedMessage()); 
     } 
    } 

fileToSave是APK文件,但写入它说没有这样的文件或目录。

java.io.FileNotFoundException:.../MyCreatedFolder/base.apk:开放 失败:ENOENT(没有这样的文件或目录)

所有必需的权限,有和运行时TargetSDK为21时不需要权限。

如何将此文件保存到我的存储目录。

+2

您是否在清单文件中提到了所需的权限?另外,从Android M开始,您需要实现运行时权限。 –

+0

是的,我已经添加了权限,并且TargetSDK不是必需的,运行时权限是21.更新了具有相同信息的问题。 – Akshat

回答

0

请尝试此代码,因为您想创建一个文件夹(如果它不存在),然后写入到您创建/指定的相同确切文件夹中,因此省略此行File path = new File(context.getFilesDir(), folderName);,而是我们创建的文件夹的路径。

private void createDirectoryAndSaveFile(File fileToSave) { 
    try { 
     String folderName = "MyCreatedFolder"; 
     String dire = Environment.getExternalStorageDirectory().toString(); 
     File dir = new File(dire +"/"+ folderName); 
     boolean success = true; 
     if (!dir.exists()) { 
      success=dir.mkdirs(); 
     } 

     if (success) { 
      File mypath = new File(dir + "/"+folderName+"/", fileToSave.getName());    
      new BufferedWriter(new FileWriter(mypath)); 
      Toast.makeText(context, "Created", Toast.LENGTH_LONG).show(); 
     } else { 
      Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show(); 
     } 
    } catch (Exception e) { 
     System.out.println("----" + e.getLocalizedMessage()); 
    } 
} 
+0

OP为什么要尝试你的代码?你能解释一下吗? –

+0

新编辑已作出解释 – Mushirih

+0

没有不工作。是否有可能我以错误的方式生成apk。?我已经更新了如何生成apk文件的问题。 – Akshat

相关问题