Android中的文件命名错误

时间:2017-01-10 18:55:57

标签: java android sqlite

大家好我在将指定文件导出到我的应用程序Sqlite数据库名称的设备内部存储时遇到问题。 我收到了错误

java.io.FileNotFoundException:/storage/emulated/0/Download/:/09/12/2017-JDO.db:open failed:ENOENT(没有这样的文件或目录)

尝试命名文件/ 09/12 / 2017-JDO时。 我使用传递的文件名File.pathSeparator(),但仍然没有运气。我认为它与文件名中的/有关,这就是我尝试File.pathSeparator()开始的原因,因为如果用户想要以该格式包含日期或者想要包含该格式的日期,我希望该选项用于命名文件与/.

结合使用

以下是我使用的方法的一些代码片段,以尝试完成此操作并显示我正在尝试执行的操作。

 /*
    This method saves and exports the current database to the device's internal Downloads folder
    This is the default named database
    */
    public void backUpDatabase() {
        /* Open your local db as the input stream */
        DBHelper anotherDbHelper = null;
        try {
            try {
                anotherDbHelper = new DBHelper(ExistingTallyActivity.this);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        String path = null;
        if (anotherDbHelper != null) {
            path = String.valueOf(getApplicationContext().getDatabasePath(anotherDbHelper.getDatabaseName()));
        }

        File dbFile = null;
        if (path != null) {
            dbFile = new File(path);
        }

        FileInputStream fis = null;
        try {
            if (dbFile != null) {
                fis = new FileInputStream(dbFile);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        String outFileName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/Pipe_Tally");

        /* Open the empty db as the output stream */
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(outFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        /* Transfer bytes from the input-file to the output-file */
        byte[] buffer = new byte[1024];
        int length;
        try {
            if (fis != null) {
                while ((length = fis.read(buffer)) > 0) {
                    try {
                        if (outputStream != null) {
                            outputStream.write(buffer, 0, length);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        /* Close the streams */
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (anotherDbHelper != null) {
            anotherDbHelper.close();
        }
    }

    /*
    This method renames the database to what the user inputs they want. Note: The original db is
    still present and stored in the Downloads folder as well.
     */
    public void renameDbFile(String desiredDbName) {
        /* Open your local db as the input stream */
        DBHelper dbHelperToRename = null;
        try {
            try {
                 dbHelperToRename = new DBHelper(ExistingTallyActivity.this);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        String pathRenamed = null;
        if (dbHelperToRename != null) {
            pathRenamed = String.valueOf(getApplicationContext().getDatabasePath(dbHelperToRename.getDatabaseName()));
        }

        File dbFileRenamed = null;
        if (pathRenamed != null) {
            dbFileRenamed = new File(pathRenamed);
        }

        FileInputStream fisRenamed = null;
        try {
            if (dbFileRenamed != null) {
                fisRenamed = new FileInputStream(dbFileRenamed);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        /* Here is where the db is renamed by the user by inserting the passed in string to the method */
        String outFileNameRenamed =
                (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .getAbsolutePath() + "/"+desiredDbName+".db");

        // Open the empty db as the output stream
        OutputStream outputStreamRenamed = null;
        try {
            outputStreamRenamed = new FileOutputStream(outFileNameRenamed);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        /* Transfer bytes from the input-file to the output-file */
        byte[] bufferRenamed = new byte[1024];
        int length;
        try {
            if (fisRenamed != null) {
                while ((length = fisRenamed.read(bufferRenamed)) > 0) {
                    try {
                        if (outputStreamRenamed != null) {
                            outputStreamRenamed.write(bufferRenamed, 0, length);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        /* Close the streams */
        try {
            if (outputStreamRenamed != null) {
                outputStreamRenamed.flush();
                outputStreamRenamed.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fisRenamed != null) {
                fisRenamed.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (dbHelperToRename != null) {
            dbHelperToRename.close();
        }
    }

    /*
    This method exports the database into CSV format as well by naming it the passed in string value
    for the desired name.
    */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void saveDbAsCsv(String desiredCsvName) {
        /* Getting a instance of the DbHelper class right here. */
        DBHelper dbhelperCsv = null;
        try {
            dbhelperCsv = new DBHelper(ExistingTallyActivity.this);
        } catch (ClassNotFoundException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        /* Original name of the file dir where the db will be stored in csv format. (Just like SQLite) */
        String pathRenamedCsv = null;
        if (dbhelperCsv != null) {
            pathRenamedCsv = String.valueOf(getApplicationContext().getDatabasePath(dbhelperCsv.getDatabaseName()));
        }
        /* Creating a File type here with the passed in name from above from the string */
        File dbFile = getDatabasePath(pathRenamedCsv);
        /*
        Appending the desired name to the Downloads Directory here, which is where the new file
        will be written
        */
        String renamedCsvName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/"+desiredCsvName);
        File exportDir = new File(String.valueOf(renamedCsvName));
        if (!exportDir.exists())
        {
            exportDir.mkdirs();
        }

        /*
        Critical .csv extension here. Took me a while originally to figure out where to pass this
        in at. Was at first passing it into the renamedCsvName up above and it was just returning
        a folder with the .csv extension and not the file contained withn.
        */
        File file = new File(exportDir, desiredCsvName+".csv");
        try
        {
            /* Passing in the string value of the file to an instance of the CsvWriter class */
            CsvWriter csvWriter = new CsvWriter(String.valueOf(file));
            SQLiteDatabase db = null;
            if (dbhelperCsv != null) {
                db = dbhelperCsv.getReadableDatabase();
            }
            /* Getting a cursor from the database table Tally_File */
            Cursor curCSV = null;
            if (db != null) {
                curCSV = db.rawQuery("SELECT * FROM Tally_File",null);
            }
            if (curCSV != null) {
                csvWriter.writeRecord(curCSV.getColumnNames());
            }
            if (curCSV != null) {
                while(curCSV.moveToNext())
                {
                    /* Exporting all the columns here to write out to the csv file */
                    String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2),
                            curCSV.getString(3), curCSV.getString(4), curCSV.getString(5),
                            curCSV.getString(6), curCSV.getString(7), curCSV.getString(8),
                            curCSV.getString(9), curCSV.getString(10), curCSV.getString(11),
                    curCSV.getString(12), curCSV.getString(13), curCSV.getString(14), curCSV.getString(15),
                    curCSV.getString(16)};
                    /*
                    Critical here as I was not at first calling the writeRecord that accepted the
                    String[] array and was calling the toString() method on it and only getting a large
                    array.
                    */
                    csvWriter.writeRecord(arrStr);
                }
            }
            csvWriter.close();
            if (curCSV != null) {
                curCSV.close();
            }
        }
        catch(Exception sqlEx)
        {
            Toast.makeText(this, "Error naming file", Toast.LENGTH_LONG).show();
        }
    }

这里是我调用方法并传入desiredName以命名文件/ Db,这是一个依赖于菜单选择的switch case,都在同一个活动中。

case R.id.menu_save_and_export:
                Thread threadMenuSaveAndExport = new Thread();
                /*
                This method verifies user permissions then calls the backUpDatabase() method to
                backup the original db file before the user renames it, if desired.
                */
                verifyStoragePermissions(new Runnable() {
                    @Override
                    public void run() {
                        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                        /* Calling this method here to backup the current database*/
                        backUpDatabase();
                    }
                });
                /* Loading the view of activity_database_name with this LayoutInflater*/
                View view = LayoutInflater.from(ExistingTallyActivity.this)
                        .inflate(R.layout.activity_database_name,null);
                /*This editText handles the input from the user for their chosen db name*/
                mEtCustomDbName = (EditText) view.findViewById(R.id.etCustomDbName);
                AlertDialog.Builder alert = new AlertDialog.Builder(ExistingTallyActivity.this);
                /* Taken from the strings.xml file. Says Name Database Prior To Export */
                alert.setMessage(getResources().getString(R.string.name_your_db));
                alert.setView(view);
                /* Using the global "Ok" string from strings.xml */
                alert.setPositiveButton(getResources().getString(R.string.global_ok_text), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                                /* Passing in the results of the editText to a string here*/
                        String userDefinedDbName = mEtCustomDbName.getText().toString().trim();
                                /*
                                Calling this method to rename the existing db to what the user input
                                Note: The original db remains in the same folder, as it was previously
                                backed up from the backUpDatabase() method above. Using the if statement
                                below to check for a empty string and if it is, the file is not renamed.
                                Both situations display custom toast message dependent on which executes.
                                Also implementing the File.separator method to help with File naming
                                issues on the Android "Unix-like" filesystem
                                */
                        if (userDefinedDbName.length() > 0) {
                            /* Naming to a .db extension with this method. Works with SQLite */
                            renameDbFile(File.pathSeparator+userDefinedDbName);
                            /* Naming to a .csv extension with this method for working with Excel */
                            saveDbAsCsv(File.pathSeparator+userDefinedDbName);
                            Toast.makeText(ExistingTallyActivity.this,
                                    /* Using the "Database Saved" string from strings.xml */
                                    getResources().getString(R.string.database_saved),
                                    Toast.LENGTH_LONG).show();
                        }else {
                            Toast.makeText(ExistingTallyActivity.this,
                                    /* Using the "Database Not Saved" string from strings.xml */
                                    getResources().getString(R.string.database_not_saved),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });
                /* Using the global "Cancel" string from strings.xml */
                alert.setNegativeButton(getResources().getString(R.string.global_cancel_text), null);
                alert.setCancelable(false);
                AlertDialog showAlert = alert.create();
                showAlert.show();
                threadMenuSaveAndExport.start();
                break;

我会非常感谢任何建议或帮助,因为我希望能够使用/如果需要使用命名作为选项。感谢

0 个答案:

没有答案