代码之家  ›  专栏  ›  技术社区  ›  Pentium10

我得到文件的父目录对于SD卡导出是不可写的

  •  0
  • Pentium10  · 技术社区  · 15 年前

    public static class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
        private Context ctx;
    
        /**
         *
         */
        public ExportDatabaseFileTask(Context ctx) {
            super();
            this.ctx = ctx;
        }
    
        // automatically done on worker thread (separate from UI thread)
        protected Boolean doInBackground(final String... args) {
    
            File dbFile = new File(Environment.getDataDirectory()
                    + "/data/com.mypkg/databases/log.db");
    
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }
            File file = new File(exportDir, dbFile.getName());
    
            try {
                file.createNewFile();//*
                this.copyFile(dbFile, file);
                return true;
            } catch (IOException e) {
                Log.e("mytag", e.getMessage(), e);
                return false;
            }
        }
    
        // can use UI thread here
        protected void onPostExecute(final Boolean success) {
            if (success) {
                Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
            }
        }
    
        void copyFile(File src, File dst) throws IOException {
            FileChannel inChannel = new FileInputStream(src).getChannel();
            FileChannel outChannel = new FileOutputStream(dst).getChannel();
            try {
                inChannel.transferTo(0, inChannel.size(), outChannel);
            } finally {
                if (inChannel != null)
                    inChannel.close();
                if (outChannel != null)
                    outChannel.close();
            }
        }
    
    }
    

    在…的标记线上

    file.createNewFile();
    

    我明白了 java.io.IOException: Parent directory of file is not writable: /sdcard/log.db

    1 回复  |  直到 15 年前
        1
  •  4
  •   Pentium10    15 年前

    当有人匆忙的时候,它会犯错误

    这是一个失踪的许可

    <uses-permission
            android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>