有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将文件读取权限设置为安卓中的文件

我正在写一个应用程序,下载一个*。从url下载apk,然后尝试安装它。 在尝试让PackageManager安装时,我似乎遇到了权限被拒绝的错误。 我想将文件的权限设置为可从java代码读取。你是怎么做到的

以下是我阅读文件的方式

InputStream input = new BufferedInputStream(url.openStream());
 OutputStream output = new FileOutputStream(PATH + fileName);

 byte data[] = new byte[1024];


 int count;

while((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
}

共 (3) 个答案

  1. # 1 楼答案

    如果您想更改android 2.2及更高版本上的文件权限,可以使用:

    Runtime.getRuntime().exec("chmod 777 " + PATH + fileName);
    

    在android 3中,您也可以不使用本机代码解决方案来实现这一点:

    new java.io.File(PATH + fileName).setReadable(true, false);
    
  2. # 2 楼答案

    你不能安装。apk文件直接使用PackageManager。只有系统应用程序才能做到这一点

    但您可以要求系统使用标准安装工作流安装应用程序。下面是一个例子:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(new File(pathToApk));
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    startActivity(intent);
    

    这一切都假设你真的成功下载了.apk。但是如果你在那一步失败了,你应该检查你的WRITE_EXTERNAL_STORAGE权限。并检查您的SD卡是否未通过USB共享(如果是,您的应用程序将没有SD卡的写入权限)

  3. # 3 楼答案

    我还没有尝试这里要问的问题,但这将改变任何版本android中的文件权限:

    exec("chmod 0777 " + fileOfInterest.getAbsolutePath());  //whatever permissions you require
    
    private void exec(String command) {
        Runtime runtime = Runtime.getRuntime();
        Process process;
        try {
            process = runtime.exec(command);
            try {
                String str;
                process.waitFor();
                BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                while ((str = stdError.readLine()) != null) {
                    Log.e("Exec",str);
                    mErrOcc = true;  //I use this elsewhere to determine if an error was encountered
                }
                process.getInputStream().close();
                process.getOutputStream().close();
                process.getErrorStream().close();
            } catch (InterruptedException e) {
                mErrOcc = true;
            }
        } catch (IOException e1) {
            mErrOcc = true;
        }
    }
    

    这就像Shmuel所建议的,但更完整,顺便说一句,他所建议的在1.5和更高版本中有效,而不是2.2和更高版本