找不到Android FileInputStream异常文件

时间:2018-11-24 22:21:37

标签: java android tar

我正在尝试用jtar解压缩tar,然后得到

  

java.io.FileNotFoundException:下载/Data.tar(无此类文件或目录)

我不使用模拟器,它直接在我的手机上。

该文件确实存在于我的android的downloads文件夹中(甚至在应用启动之前)。

我拥有读取/写入的所有权限。

File tarFile = new File(Environment.DIRECTORY_DOWNLOADS, "Data.tar");
        File destFolder = new File(Environment.DIRECTORY_DOCUMENTS + "/My Data/");
        if(!destFolder.exists())
        {
            // Make it, if it doesn't exit
            destFolder.mkdirs();
        }else{
            //TODO
            //delete the folder contents
        }


        // Create a TarInputStream
        try {
            TarInputStream tis = new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile)));
            TarEntry entry;

            while ((entry = tis.getNextEntry()) != null) {
                int count;
                byte data[] = new byte[2048];
                FileOutputStream fos = new FileOutputStream(destFolder + "/" + entry.getName());
                BufferedOutputStream dest = new BufferedOutputStream(fos);

                while ((count = tis.read(data)) != -1) {
                    dest.write(data, 0, count);
                }

                dest.flush();
                dest.close();
            }

            tis.close();
        }catch (Exception e){
            Toast toast2 = Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG);
            toast2.show();
            Log.e("TAG", "error", e);
        }

Logcat表示错误在尝试后的第一行

编辑:由于某些原因,即使在调试时它也转到destFolder.mkdirs();,它甚至都没有创建/ My Data /文件夹。不确定如何关联

编辑2:我发现tarFile.exists()tarFile.canRead()说的是错误的,我试图给出一条明确的路径"storage/emulated/0/Download/Data.tar"并且有效,它存在并且可读。

像这样留下危险吗?某些手机​​会使用不同的...emullated/X/...号吗?

2 个答案:

答案 0 :(得分:0)

如果设备的android版本大于6.0,则仅在AndroidManifest xml中声明权限请求是不够的。您还应该明确请求任何需要许可的操作。

if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    // Permission is not granted
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
            new String[] {
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            },
            MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
    }
}

答案 1 :(得分:0)

我解决了!

table1

即使您将编写Function test() With SearchQuery("Your Search Query").OpenRecordset If Not .EOF Then .MoveFirst Do Until .EOF Debug.Print !Field1 .MoveNext Loop End If .Close End With End Function ,也会尝试从您的应用程序获取相对路径。

解决方案? File tarFile = new File(Environment.DIRECTORY_DOWNLOADS, "Data.tar");