簡體   English   中英

Android如何保存文件?

[英]How Android Saving Files?

我需要將一些文件保存到我的Android手機中。 所以我用了類似的東西:

FileOutputStream os = null;
 try{
     os = new FileOutputStream("/root/sdcard/DCIM/1.jpg");
     os.write(bytes);
     os.close();
 }catch(FileNotFoundException e){}

當我這樣做時,它會說類似

java.io.FileNotFoundException: /root/sdcard/DCIM/1.jpg (Permission denied)

順便說一句,我已經使用以下方法在AndroidManifest.xml中請求了權限:

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

我也試過

getFilesDir().getAbsolutePath();

它實際上是指

/data/user/0/come.package.xxx/files

我不知道該路徑在哪里,因為我無法在手機上找到它。 當我使用ASUS File Manager時,我看到的路徑是/ root / sdcard / ...,但是我的手機中甚至沒有sdcard,我已經使用iPhone多年了,所以我不知道Android文件系統現在如何工作。

這真的讓我感到困惑,有人可以向我解釋一下Android文件系統的工作原理嗎? 謝謝你們!

在Android上保存圖像:

private String saveToInternalStorage(String name, Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(context);
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir(IMAGE_TAG, Context.MODE_PRIVATE);
        // Create imageDir
        File mypath = new File(directory, name + ".jpg");

        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return directory.getAbsolutePath();
    }

加載圖像:

public void loadImage(ImageView imageView) {
        // get path
        ContextWrapper cw = new ContextWrapper(context);
        File directory = cw.getDir(IMAGE_TAG, Context.MODE_PRIVATE);
        String path = directory.getAbsolutePath();

        // load image
        try {
            File f = new File(path, name + ".jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            imageView.setImageBitmap(b);
            imageView.setVisibility(View.VISIBLE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("Image", "Image file not found.");    
        }
}

如果您使用的是Android 6.0 Marsh或更高版本的Android,則需要授予運行時訪問access.try的權限,代碼如下

  if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            camera.setEnabled(false);
           ActivityCompat.requestPermissions(getActivity(), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
       }
 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                //permission will get success here
                //do what you want
            }
            else {
                //Permission not granted
                Toast.makeText(getActivity(),"You need to grant camera permission to use camera",Toast.LENGTH_LONG).show();
            }
        }
    }

如果您使用的是棉花糖或最新版本的android,則需要在運行時提供權限,然后單擊按鈕即可調用將代碼保存到SD卡的代碼。

比做完之后

public void onClick(View v) {
    // write on SD card file data in the text box
    try {
        File myFile = new File("/sdcard/mysdfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = 
                                new OutputStreamWriter(fOut);
        myOutWriter.append(txtData.getText());
        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(),
                "Done writing SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM