(没有这样的文件或目录)在android上从外部存储导入sqlite db时出错

y0u0uwnf  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(344)

我尝试给我的用户提供导入和导出数据库的选项。每当我尝试导入文件时,都会出现以下错误:
e/tag:/storage\u root/appname/mydb(没有这样的文件或目录)
目录似乎是正确的,但不知何故我永远无法打开/复制文件。我已经试过很多不同的选择了。所有这些代码都在一个片段中。
代码:

importSQL.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            startActivityForResult(intent, GET_DB);
        }
    });

//

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i("OnActivityResultImport", "Bitmap was selected " + requestCode + "   " + resultCode);

    if (resultCode == Activity.RESULT_OK){

        switch (requestCode) {
            case GET_DB:
                Uri selectedImage = data.getData();

                //Find DB to import

                String PathHolder = data.getData().getPath();

                importDB(PathHolder);
                break;
        }
    }
}

//

public void importDB(String path){

    if(isExternalStorageWritable()) {

        //check if it really is a valid SQL DB file
        if(isValidSQLite(path)) {

            String outputPath = exportSQL.getContext().getFilesDir().getAbsolutePath().split("files")[0] + "databases/";
            Log.d("WritingDB", "storage is writeable\nReading DB from: " + path);

            String outputFile = "MYDB";
            InputStream in = null;
            OutputStream out = null;
            try {

                //create output directory if it doesn't exist
                File dir = new File(outputPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                in = new FileInputStream(path);
                out = new FileOutputStream(outputPath + outputFile);

                byte[] buffer = new byte[1024];
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                in = null;

                // write the output file
                out.flush();
                out.close();
                out = null;

            } catch (FileNotFoundException fnfe1) {
                Log.e("tag", fnfe1.getMessage());
            } catch (Exception e) {
                Log.e("tag", e.getMessage());
            }

            Toast.makeText(getContext(), R.string.exportSuccessMessage, Toast.LENGTH_LONG).show();

        }else{
            Toast.makeText(getContext(), "Thats not a valid DB!", Toast.LENGTH_LONG).show();

        }
    }
}

非常感谢您的帮助:)

7nbnzgx9

7nbnzgx91#

只有当db目录的路径不正确时,才会出现此错误。尝试在代码中放置绝对路径(都是静态文件夹名)。

相关问题