How to remove FileNotFoundException: exception in

2019-07-31 02:49发布

FilePath =/external/images/media/2

Getting error : java.io.FileNotFoundException: /external/images/media/2 (No such file or directory)

Hi I am tring to upload the selected image on server .I am getting this error java.io.FileNotFoundException: /external/images/media/2 (No such file or directory).Actually I am checking this on simulator.First I select the image from gallery then get the bytes of selected image.but I am getting error file not found why

here is my code :

package com.CA.xmlparsing;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends Activity {

    private static final int PICKFILE_RESULT_CODE = 2;
    private String FilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void upLoadImage(View view) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                PICKFILE_RESULT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }

    }  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Fix no activity available
        if (data == null)
            return;
        switch (requestCode) {
        case PICKFILE_RESULT_CODE:
            if (resultCode == RESULT_OK) {
                 FilePath = data.getData().getPath();
                //FilePath is your file as a string
                Log.d("--------------", FilePath);
// print /external/images/media/2
                byte[] bytes=  getFileByte(FilePath);
                Log.d("--------------", ""+bytes);
            }
        }
    }

  private   byte [] getFileByte(String path){
         File file = new File(path);
            int size = (int) file.length();
            byte[] bytes = new byte[size];
            try {
// getting error on this line
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                buf.read(bytes, 0, bytes.length);
                buf.close();
            } catch (FileNotFoundException e) {
//catch here the error
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return bytes;
    }
}


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.CA.xmlparsing.MainActivity" >

 <Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="uploadImage"
     android:onClick="upLoadImage" />

</RelativeLayout>

is there any permission required for thar to read image from emulator ?

标签: android
3条回答
smile是对你的礼貌
2楼-- · 2019-07-31 03:15

What you get is not a file path for the file system but a media path in use by mediastore and others. In order to get a real filepath you have to invoke a cursor on the media store. You can find many example codes on this site.

查看更多
混吃等死
3楼-- · 2019-07-31 03:37

Your real issue is to convert the image into byte so you can Upload on to a server. The onActivityResult method will provide you with a Bitmap object.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap bmp = (Bitmap) data.getExtras().get("data"); 
    }  
}

Now instead of getting the Path, then converting it into File and then again converting it into bytes, you can directly use the bitmap object that you get from onActivityResult method and use the below method to convert it into bytes.

public byte[] bitmapToByte(Bitmap bitmap){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

But this post is asking "How to remove FileNotFoundException: exception in android?", so to get the path of the image you need to:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 

        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // CALL THIS METHOD TO GET THE ACTUAL PATH
        File finalFile = new File(getAbsolutePathFromURI(tempUri));
    }  
}

public Uri getImageUri(Context context, Bitmap bitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(context.getContentResolver(), bitmap, "TempImage", null);
    return Uri.parse(path);
}

public String getAbsolutePathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(index); 
}
查看更多
混吃等死
4楼-- · 2019-07-31 03:37

There are permissions that you need to add to your android manifest although this may not be your only problem. Add:

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

查看更多
登录 后发表回答